I am configuring a scheduled task to run in different threads. Here is the configuration code
@Configuration
@EnableScheduling
public class SchedulerConfig implements SchedulingConfigurer {
private final int POOL_SIZE = 10;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
threadPoolTaskScheduler.setThreadNamePrefix("my-sched-pool-");
threadPoolTaskScheduler.initialize();
scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
}
}
Here is the code that uses it
@Scheduled(fixedRateString = "2000" )
public void testaMethod() {
log.debug("here is the message");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
I am sleeping the thread for 10s with fixedRate of 2s. so I expect to see different threads in the log but I see only one
logs are here
{"thread":"my-sched-pool-1","level":"DEBUG","description":"here is the message"}
{"thread":"my-sched-pool-1","level":"DEBUG","description":"here is the message"}
{"thread":"my-sched-pool-1","level":"DEBUG","description":"here is the message"}
{"thread":"my-sched-pool-1","level":"DEBUG","description":"here is the message"}
@Scheduled(fixedRateString = "2000" )
does not guranteetestaMethod
be executed every 2 seconds, if the time cost is more than 2s, such asThread.sleep(10000)
, the new task will be put in a queue. Only when the old one has been executed, the scheduler will fetch the new task from queue and execute it. Since the new task is now the only task in the scheduler, it could be run without creating a newThread
.To solve this problem, you can combile @Async and @Scheduled
SchedulerConfig
SchedulerTask
AsyncTask
Test results