@Component
@Slf4j
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
private List<Integer> index = Arrays.asList(6, 6, 2, 3);
int i = 0;
@Scheduled(fixedRate = 5000)
public void reportCurrentTimeWithFixedRate() {
if (i == 0) {
log.info("Start time is {}", dateFormat.format(new Date()));
}
if (i < 5) {
try {
TimeUnit.SECONDS.sleep(index.get(i));
log.info("Fixed Rate Task : The time is now {}", dateFormat.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
}
}
运行程序输出如下:
Start time is 09:26:41
Fixed Rate Task : The time is now 09:26:47
Fixed Rate Task : The time is now 09:26:53
Fixed Rate Task : The time is now 09:26:55
Fixed Rate Task : The time is now 09:26:59
示意图:
自定义线程池
默认情况下,@Scheduled 任务都在 Spring 创建的大小为 1 的默认线程池中执行,你可以通过在加了 @Scheduled 注解的方法里加上下面这段代码来验证。
@Configuration
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-scheduled-task-pool-");
threadPoolTaskScheduler.initialize();
scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
}
}
并发执行
测试代码:
@Slf4j
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedDelay = 2000)
public void reportCurrentTimeWithFixedDelay() {
try {
TimeUnit.SECONDS.sleep(3);
log.info("Fixed Delay Task : The time is now {}", dateFormat.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
[scheduling-1] : Fixed Delay Task : The time is now 09:45:12
[scheduling-1] : Fixed Delay Task : The time is now 09:45:17
[scheduling-1] : Fixed Delay Task : The time is now 09:45:22
[scheduling-1] : Fixed Delay Task : The time is now 09:45:27
[scheduling-1] : Fixed Delay Task : The time is now 09:45:32
[scheduling-1] : Fixed Delay Task : The time is now 09:45:37
添加 @EnableAsync 和 @Async 这两个注解让任务并行执行:
@Slf4j
@EnableAsync
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Async
@Scheduled(fixedDelay = 2000)
public void reportCurrentTimeWithFixedDelay() {
/* .... */
}
}
[lTaskExecutor-1] : Fixed Delay Task : The time is now 09:44:04
[lTaskExecutor-2] : Fixed Delay Task : The time is now 09:44:06
[lTaskExecutor-3] : Fixed Delay Task : The time is now 09:44:08
[lTaskExecutor-4] : Fixed Delay Task : The time is now 09:44:10
[lTaskExecutor-5] : Fixed Delay Task : The time is now 09:44:12
[lTaskExecutor-6] : Fixed Delay Task : The time is now 09:44:14