目录
一、springboot使用方法:
较为简单,直接上代码。
1.首先在springboot启动类上加上@EnableScheduling注解
示例:
@SpringBootApplication
@EnableScheduling
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
2.新建定时任务类,看代码:
@Component
public class ITask {
//每5秒执行一次
@Scheduled(cron = "0/5 * * * * ?")
public void printSay() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
String time = sdf.format(date);
System.out.println(time+"执行了一次");
}
}
看执行结果:
二、cron表达式详解:
按顺序依次为:
顺序 字段 取值范围 允许的特殊字符
1 秒 0~59 , - * /
2 分 0~59 , - * /
3 时 0~23 , - * /
4 日 1~31 , - * ? / L W C
5 月 1~12 , - * /
6 星期 0~7 (SUN=0或7,或SUN-SAT) , - * ? / L C #
7 年份 1970~2099(可有可无) , - * /
其中每个元素可以是一个数值(如6)、一个连续区间(如9-12)、一个间隔时间(如8-18/4,/表示每隔4小时)、一个列表(如1,3,5)、通配符。由于“月份中的日期”和“星期中的日期”这两个元素互斥的,必须要对其中一个设置“?”
示例:(看了就懂)
"0 0 10,14,16 * * ?" //每天上午10点,下午2点,4点
"0 0/30 9-17 * * ?" //朝九晚五工作时间内每半小时
"0 0 12 ? * WED" //表示每个星期三中午12点
"0 0 12 * * ?" //每天中午12点触发
"0 15 10 ? * *" //每天上午10:15触发
"0 15 10 * * ?" //每天上午10:15触发
"0 15 10 * * ? *" //每天上午10:15触发
"0 15 10 * * ? 2005" //2005年的每天上午10:15触发
"0 * 14 * * ?" //在每天下午2点到下午2:59期间的每1分钟触发
"0 0/5 14 * * ?" //在每天下午2点到下午2:55期间的每5分钟触发
"0 0/5 14,18 * * ?" //在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
"0 0-5 14 * * ?" //在每天下午2点到下午2:05期间的每1分钟触发
"0 10,44 14 ? 3 WED" //每年三月的星期三的下午2:10和2:44触发
"0 15 10 ? * MON-FRI" //周一至周五的上午10:15触发
"0 15 10 15 * ?" //每月15日上午10:15触发
"0 15 10 L * ?" //每月最后一日的上午10:15触发
"0 15 10 ? * 6L" //每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6L 2002-2005" //2002年至2005年的每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6#3" //每月的第三个星期五上午10:15触发