1 demo
package com.test.domi.config;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
@Configurable
@EnableScheduling
public class ScheduledTasks {
//每30秒执行一次
@Scheduled(fixedRate = 1000 * 30)
public void reportCurrentTime(){
System.out.println ("Scheduling Tasks Examples: The time is now " + dateFormat ().format (new Date ()));
}
//在固定时间执行
@Scheduled(cron = "0 */1 * * * * ")
public void reportCurrentByCron(){
System.out.println ("Scheduling Tasks Examples By Cron: The time is now " + dateFormat ().format (new Date()));
}
private SimpleDateFormat dateFormat(){
return new SimpleDateFormat ("HH:mm:ss");
}
}
Scheduling Tasks Examples: The time is now 11:55:54 Scheduling Tasks Examples By Cron: The time is now 11:56:00 Scheduling Tasks Examples: The time is now 11:56:24 Scheduling Tasks Examples: The time is now 11:56:54 Scheduling Tasks Examples By Cron: The time is now 11:57:00
2 详解
http://tramp.cincout.cn/2017/08/18/spring-task-2017-08-18-spring-boot-enablescheduling-analysis/
cron表达式:https://www.zhyd.me/article/43
3 总结
默认的 ConcurrentTaskScheduler 计划执行器采用Executors.newSingleThreadScheduledExecutor() 实现单线程的执行器。因此,对同一个调度任务的执行总是同一个线程。如果任务的执行时间超过该任务的下一次执行时间,则会出现任务丢失,跳过该段时间的任务。上述问题有以下解决办法:
采用异步的方式执行调度任务,配置 Spring 的 @EnableAsync,在任务执行的方法上标注 @Async配置任务执行池,采用 ThreadPoolTaskScheduler.setPoolSize(n)。 n 的数量为 单个任务执行所需时间 / 任务执行的间隔时间
spring自带的定时任务功能@EnableScheduling
原文:https://www.cnblogs.com/domi22/p/9418433.html