Spingboot实现定时任务
定时任务创建
在Spring Boot
项目中,需要在启动类上添加@EnableScheduling
来开启定时任务
@EnableScheduling // 开启定时任务
@SpringBootApplication
public class Job4ScheduledApplication {public static void main(String[] args) {SpringApplication.run(Job4ScheduledApplication.class, args);}
}
之后创建定时任务文件
@Component //@Component用于实例化类,将其类托管给 Spring 容器
public class TaskJobUtil {/* cron表达式:表示每2秒 执行任务*/@Scheduled(cron = "0/2 * * * * ?")public void task() {System.out.println("task0-start");sleep(5);System.out.println("task0-end");}/* fixedRate:每间隔2秒执行一次任务* 注意,默认情况下定时任务是在同一线程同步执行的,如果任务的执行时间(如5秒)大于间隔时间,则会等待任务执行结束后直接开始下次任务*/@Scheduled(fixedRate = 2000)public void task0() {System.out.println("task0-start");sleep(5);System.out.println("task0-end");}/* fixedDelay:每次延时2秒执行一次任务* 注意,这里是等待上次任务执行结束后,再延时固定时间后开始下次任务*/@Scheduled(fixedDelay = 2000)public void task1() {System.out.println("task1-start");sleep(5);System.out.println("task1-end");}/* initialDelay:首次任务启动的延时时间*/@Scheduled(initialDelay = 2000, fixedDelay = 3000)public void task2() {System.out.println("task2-start");sleep(5);System.out.println("task2-end");}private void sleep(long time) {try {TimeUnit.SECONDS.sleep(time);} catch (InterruptedException e) {e.printStackTrace();}}
}
cron如何填写:
Cron 在线生成
quartz/Cron/Crontab表达式在线生成工具-BeJSON.com
常用表达式例子
{秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}
(1)0/2 * * * * ? 表示每2秒 执行任务
(1)0 0/2 * * * ? 表示每2分钟 执行任务
(1)0 0 2 1 * ? 表示在每月的1日的凌晨2点调整任务
(2)0 15 10 ? * MON-FRI 表示周一到周五每天上午10:15执行作业
(3)0 15 10 ? 6L 2002-2006 表示2002-2006年的每个月的最后一个星期五上午10:15执行
(4)0 0 10,14,16 * * ? 每天上午10点,下午2点,4点
(5)0 0/30 9-17 * * ? 朝九晚五工作时间内每半小时
(6)0 0 12 ? * WED 表示每个星期三中午12点
(7)0 0 12 * * ? 每天中午12点触发
(8)0 15 10 ? * * 每天上午10:15触发
(9)0 15 10 * * ? 每天上午10:15触发
(10)0 15 10 * * ? 每天上午10:15触发
(11)0 15 10 * * ? 2005 2005年的每天上午10:15触发
(12)0 * 14 * * ? 在每天下午2点到下午2:59期间的每1分钟触发
(13)0 0/5 14 * * ? 在每天下午2点到下午2:55期间的每5分钟触发
(14)0 0/5 14,18 * * ? 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
(15)0 0-5 14 * * ? 在每天下午2点到下午2:05期间的每1分钟触发
(16)0 10,44 14 ? 3 WED 每年三月的星期三的下午2:10和2:44触发
(17)0 15 10 ? * MON-FRI 周一至周五的上午10:15触发
(18)0 15 10 15 * ? 每月15日上午10:15触发
(19)0 15 10 L * ? 每月最后一日的上午10:15触发
(20)0 15 10 ? * 6L 每月的最后一个星期五上午10:15触发
(21)0 15 10 ? * 6L 2002-2005 2002年至2005年的每月的最后一个星期五上午10:15触发
(22)0 15 10 ? * 6#3 每月的第三个星期五上午10:15触发