个人博客地址:http://alexaccele.github.io/
在springboot中让任务定时执行
首先在入口类上添加@EnableScheduling注解
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
在指定的要定时执行的任务方法上添加@Scheduled注解
@Service
public class ScheduledService {
/*秒 分 时 日 月 周
* corn中的表达式例子:0 * * * * *
* 表示每个月每周每天每时每分的0秒就会执行
* */
@Scheduled(cron = "0-50 * * * * *")
public void scheduledHello(){
System.out.println("hello...");
}
}
在注解中写上cron表达式则可以满足相应的时间要求,如实例代码中表示对于任意一分钟内的第0秒到第50秒每秒都会输出“hello...”
cron表达式
Cron表达式是一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下两种语法格式:(1)秒 分 时 日期 月 一周中的星期 年
(2)秒 分 时 日期 月 一周中的星期
字段 | 允许值 | 允许的特殊字符 |
秒(Seconds) | 0~59的整数 | , - * / |
分(Minutes) | 0~59的整数 | , - * / |
小时(Hours) | 0~53的整数 | , - * / |
日期(DayofMonth) | 1~31的整数(注意月份的天数) | , - * / ? L W C |
月份(Month) | 1~12的整数 | , - * / |
星期(DayofWeek) | 0-7或SUN-SAT,0和7是SUN | , - * / ? L C # |
特殊字符 | 含义 |
,(英文逗号) | 枚举 |
-(减号) | 区间 |
* | 任意 |
/ | 间隔步长 |
? | 日/星期冲突匹配 |
L | 最后 |
W | 工作日 |
C | 和calendar联系后计算过的值 |
# | 星期,4#2 表示第二个星期四 |