SpringBoot定时任务
修改程序入口, 添加开启定时任务的注解
@SpringBootApplication
@EnableScheduling
public class SpringbootScheduleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootScheduleApplication.class, args);
}
}
编写定时任务类@Component进行注解扫面
@Component
public class ScheduleTask {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 3000)
public void reportCurrentTime(){
System.out.println("当前时间:" + dateFormat.format(new Date()));
}
}
程序将在启动后每3秒执行
@Scheduled(fixedRate = 3000):定时器将在每隔3秒执行
@Schedule(fixedDelay = 3000):定时器将在延迟3秒后每隔3秒执行
@Schedule(initialDelay = 1000, fiexdDelay = 3000):定时器将在1秒后每隔3秒执行
@Schedule(cron = “* * * * * ?”)
一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。
按顺序依次为
秒(0~59)
分钟(0~59)
小时(0~23)
天(月)(0~31,但是你需要考虑你月的天数)
月(0~11)
天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
7.年份(1970-2099)
@Component
public class ScheduleTask {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 3000)
public void reportCurrentTime(){
System.out.println("当前时间:" + dateFormat.format(new Date()));
}
//第一次延迟1秒执行,当执行完后3秒再执行
@Scheduled(initialDelay = 1000, fixedDelay = 3000)
public void timerInit() {
System.out.println("init : "+dateFormat.format(new Date()));
}
//每天19点50分50秒时执行
@Scheduled(cron = "50 50 19 * * ?")
public void timerCron() {
System.out.println("current time : "+ dateFormat.format(new Date()));
}
}
本文介绍了如何在SpringBoot中配置并使用定时任务。通过添加@EnableScheduling注解启动定时功能,并利用@Scheduled注解实现固定频率及基于cron表达式的调度方式。文章提供了多个示例,包括简单的每三秒执行一次的任务、首次延迟执行后定期运行的任务以及每日特定时间触发的任务。
1304

被折叠的 条评论
为什么被折叠?



