Springboot Schedule

Maven config

1
2
3
4
5
6
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>

Add @EnableScheduling annotation in application main or configuration class

Thread pool

In org.springframework.scheduling.config.ScheduledTaskRegistrar
after the after properties set, spring set a default single thread excutor.

1
2
3
4
5
6
7
8
protected void scheduleTasks() {
long now = System.currentTimeMillis();
if(this.taskScheduler == null) {
this.localExecutor = Executors.newSingleThreadScheduledExecutor();
this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
}
...
}

When the program’s schedules need time to deal with the job.
Single Thread excutor may cause job be blocked, then the job’s excuted time might be wrong.

So when the single node have hard works need be done precisely, we need a selfdefine threadpool.

1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}

@Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(20);
}
}

Close

When the web application closed, the threadpool is still alive, we need actively close it.

1
2
3
4
5
6
7
8
9
10
@Component
public class MyTask implements DisposableBean{
@Override
public void destroy() throws Exception {
ThreadPoolTaskScheduler scheduler =
(ThreadPoolTaskScheduler)applicationContext.getBean("scheduler");
scheduler.shutdown();
}
...
}

Cluster

If the schedule needs enterprise level structure, a schedule cluster is needed.
Use consistency middle ware/[DB]/[Cache] control the schedule node’s behaviour.
Use Message queue control the job’s status/ corn, even add/ remove jobs.
Spring schedule not support the persistency feature, but through mechanism it still can be resolved.
If the requirement is that level, use spring schedule may not be a good choice.

https://www.cnblogs.com/skychenjiajun/p/9057379.html
https://blog.csdn.net/qq_34125349/article/details/77430956