一、定时任务
1.1 简介
项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor、 TaskScheduler接口。
两个注解:@EnableScheduling、@Scheduled
cron表达式
启动类标注@EnableScheduling注解开启基于注解的定时任务
package com.best;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling //开启基于注解的定时任务
@SpringBootApplication
public class ScheduleApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduleApplication.class, args);
}
}
1.2.2 业务类
需要定时的方法上面,标注@Scheduled注解,并配置cron表达式,来指示什么时候执行
package com.best.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledService {
/**
* second(秒), minute(分), hour(时), day(日), month(月), week(周)
* 0 * * * * MON-FRI
*/
// @Scheduled(cron = "* * * * * *")//任意一秒
// @Scheduled(cron = "0,1,2,3 * * * * MON-SAT") //周一到周六不管哪一天哪一分,0,1,2,3秒都会执行一次
// @Scheduled(cron = "0-3 * * * * MON-SAT") //周一到周六不管哪一天哪一分,0-3秒都会执行一次
// @Scheduled(cron = "0/3 * * * * MON-SAT") //从0秒开始每3s执行一次
@Scheduled(cron = "0/3 * * 0 * ?") //日/星期冲突匹配,注意?中英文
public void hello() {
System.out.println("hello...");
}
}
1.2.3 测试
源码