给项目添加定时任务
基于注解(@Scheduled)
@Scheduled 由Spring定义,用于将方法设置为调度任务。如:方法每隔十秒钟被执行、方法在固定时间点被执行等。
使用流程:
- 首先要在启动类添加@EnableScheduling注解,开启定时任务。
- 在方法所在的类上面添加@Component注解开启扫描。
- 在方法上添加注解@Scheduled(cron = “*/5 * * * * ?”),并配置参数。(建议将参数放到配置文件中方便修改)
cron表达式:
cron表达式可实现复杂的定时任务,至少由6个(或7个)空格分隔的时间元素组成。
使用方法:
- 结构为:秒 分 小时 月份中的日期 月份 星期中的日期 年份
- 举例:
//每十秒执行一次
@Scheduled(cron = "0/10 * * * * ?")
public void hello(){
System.out.println("hello world!");
}
//每天上午十点执行一次
//如果把0写成*就会在每天上午10点钟的每秒或者每分钟都执行
@Scheduled(cron = "0 0 10 * * ?")
public void hello(){
System.out.println("hello world!");
}
//每个星期三中午12点
@Scheduled(cron = "0 0 12 ? * WED ")
public void hello(){
System.out.println("hello world!");
}
注意:
- 用@Scheduled注解修饰的方法一定不能有参数。
- cron表达式详细配置和例子可以参考下面这个文章。
Spring的@Scheduled注解使用介绍