Spring Boot项目定时任务实现
定时任务实现方式:
Spring Boot自带的Scheduled,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多。
Spring Boot项目使用定时器实现任务步骤:
1、在项目启动的main方法中,添加注解 @EnableScheduling,该注解开启对计划任务的支持
@SpringBootApplication
@EnableScheduling //开启对计划任务的支持
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2、新建任务类ScheduledJob,在方法上添加@Scheduled,Scheduled注解为定时任务,cron表达式里写执行的时间
package com.nec.config.job;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 定时任务
*/
@Component
public class ScheduledJob {
@Scheduled(cron = "0 0 0 * * ?") //每天凌晨00:00:00执行一次
public void ScheduledTask1 () throws Exception {
//调用定时任务要执行的方法
}
@Scheduled(fixedRate = 2000) //每隔两秒执行一次
public void ScheduledTask2 () throws Exception {
//调用定时任务要执行的方法
}
@Scheduled(fixedDelay = 3000) //该方法执行完毕后,延迟3秒再执行该方法
public void ScheduledTask3 () throws Exception {
//调用定时任务要执行的方法
}
}
3、 @Scheduled注解中cron、fixedRate 、fixedDelay表达式的含义
cron:一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下两种语法格式:
秒 分钟 小时 天(月) 月 天(星期) 年份
或
秒 分钟 小时 天(月) 月 天(星期)
每一个域可出现的字符如下:
按顺序依次为
秒(0~59)
分钟(0~59)
小时(0~23)
天(月)(0~31,但是你需要考虑你月的天数)
月(0~11)
天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
年份(1970-2099)