一、SpringBoot定时任务schedule
1、启动类加注解@EnableScheduling开启定时任务,自动扫描。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling //开启定时任务
public class Application {
public static void main(String[] args) {
final SpringApplication application = new SpringApplication(com.xxx.xxx.Application.class);
application.run(args);
}
}
2、定时任务业务类加注解@Component被容器扫描。
3、定时执行的方法加注解@Scheduled定期执行一次。
// 定时任务业务类
@Component
public class TestTask {
@Scheduled(fixedRate = 2000) // 两秒执行一次
public void sum() {
System.out.println("当前时间:" + new Date());
}
}
二、常用定时任务配置实战
1、cron定时任务表达式:@Scheduled(cron = “0 0/1 * * * ?”) 每分钟执行一次:
@Component
public class TestTask {
@Scheduled(cron = "0 0/1 * * * ?")
public void startTestTask(){
LOG.info("=========================定时任务开始=========================");
try{
testTaskService.run();
}catch (Exception e){
e.printStackTrace();
}
LOG.info("=========================定时任务结束=========================");
}
}
2、fixedRate:定时多久执行一次:
@Component
public class TestTask {
@Scheduled(fixedRate = 2000)
public void sum() {
System.out.println("开始的当前时间:" + new Date());
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("结束的当前时间:" + new Date());
}
}
运行结果:
开始的当前时间:Mon Mar 04 16:39:24 CST 2019
结束的当前时间:Mon Mar 04 16:39:28 CST 2019
开始的当前时间:Mon Mar 04 16:39:28 CST 2019
结束的当前时间:Mon Mar 04 16:39:32 CST 2019
开始的当前时间:Mon Mar 04 16:39:32 CST 2019
使用fixedRate:如果上一个任务未执行完毕,需要等待上一个任务执行完才能执行下一个任务。
3、fixedDelay:上一次执行结束时间点后几秒再次执行:
@Component
public class TestTask {
@Scheduled(fixedDelay = 2000)
public void sum() {
System.out.println("开始的当前时间:" + new Date());
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("结束的当前时间:" + new Date());
}
}
运行结果:
开始的当前时间:Mon Mar 04 16:41:04 CST 2019
结束的当前时间:Mon Mar 04 16:41:08 CST 2019
开始的当前时间:Mon Mar 04 16:41:10 CST 2019
结束的当前时间:Mon Mar 04 16:41:14 CST 2019
开始的当前时间:Mon Mar 04 16:41:16 CST 2019
4、fixedRateString和fixedDelayString:字符串形式,可以通过配置文件指定