在现代应用开发中,定时任务是一个常见的需求。比如,我们可能需要定时清理过期数据、定时发送邮件通知等。
操作流程
开启定时任务注解
在启动类添加注解@EnableScheduling
设置时间(固定时间间隔)
使用 @Scheduled
注解创建定时任务十分简单,只需几行代码就能完成。@Scheduled
除了支持灵活的 cron
参数表达式,还支持简单的延时操作,如 fixedDelay
(任务执行结束后延迟指定毫秒数再执行下一次)、fixedRate
(固定频率,每隔指定毫秒数执行一次)。
@EnableScheduling
@SpringBootApplication
public class DingshiApplication {
public static void main(String[] args) {
SpringApplication.run(DingshiApplication.class, args);
}
//下面的两个方法在第一次启动项目的时候会执行一次
// 半小时提醒一次
@Scheduled(fixedRate = 30*60*1000)
public void playSth1(){
System.out.println("任务一"+ DateFormat.getDateInstance().format(new Date()));
}
// 四小时执行一次
@Scheduled(fixedRate = 4*60*60*1000)
public void playSt