一 启动类中@EnableScheduling开启定时器
@SpringBootApplication
@EnableCaching
@EnableScheduling
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
二 类上加入@Component,需要定时的方法上加上注解@Scheduled(cron=“0/5 * * * * ?”)表示5s执行一次
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
/**
* 每五秒执行一次
*/
@Scheduled(cron="0/5 * * * * ?")
public void scheduledTasks(){
System.out.println("The time is now {}" + dateFormat.format(new Date()));
}
}
The time is now {}14:55:15
The time is now {}14:55:20
The time is now {}14:55:25
The time is now {}14:55:30
The time is now {}14:55:35
The time is now {}14:55:40
The time is now {}14:55:45
The time is now {}14:55:50
The time is now {}14:55:55
The time is now {}14:56:00
OK,大公告成!
cron属性的使用
这是一个时间表达式,可以通过简单的配置就能完成各种时间的配置,我们通过CRON表达式几乎可以完成任意的时间搭配,它包含了六或七个域:
- Seconds : 可出现", - * /"四个字符,有效范围为0-59的整数
- Minutes : 可出现", - * /"四个字符,有效范围为0-59的整数
- Hours : 可出现", - * /"四个字符,有效范围为0-23的整数
- DayofMonth : 可出现", - * / ? L W C"八个字符,有效范围为0-31的整数
- Month : 可出现", - * /"四个字符,有效范围为1-12的整数或JAN-DEc
- DayofWeek : 可出现", - * / ? L C #"四个字符,有效范围为1-7的整数或SUN-SAT两个范围。1表示星期天,2表示星期一, 依次类推
- Year : 可出现", - * /"四个字符,有效范围为1970-2099年
推荐一个在线Cron表达式生成器http://cron.qqe2.com/
几个简单例子
“0 0 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分每分钟一次触发
“0 0/5 14 * * ?” 每天从下午2点开始到2:55分结束每5分钟一次触发
“0 0/5 14,18 * * ?” 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
“0 0-5 14 * * ?” 每天14:00至14:05每分钟一次触发
“0 10,44 14 ? 3 WED” 三月的每周三的14:10和14:44触发
“0 15 10 ? * MON-FRI” 每个周一、周二、周三、周四、周五的10:15触发
版权声明:本文为qq_41583016原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。