前几节咱们用第三方框架quarz实现了定时任务,实际上spring3.1开始,spring已经内置了定时任务的支持,实现很是简单,下面咱们一块儿看看怎么实现java
其中重点是@EnableScheduling注解,表示启动定时任务支持spring
package com.cppba; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class ScheduleApplication { public static void main(String[] args) { SpringApplication.run(ScheduleApplication.class, args); } }
package com.cppba.schedule; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; @Component public class SaySchedule { private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Scheduled(cron = "0/2 * * * * ?") public void sayHi() { System.out.println("hi! time is :" + df.format(new Date())); } @Scheduled(cron = "1/2 * * * * ?") public void sayHello() { System.out.println("hello! time is :" + df.format(new Date())); } }
核心重点是@Scheduled注解,@Scheduled支持多种类型的计划任务:cron、fixDelay、fixRate,最流行的仍是cron表达式,
在这里推荐一个cron表达式在线生成器:http://cron.qqe2.com/框架
功能很强大,能够图形化配置cron表达式,也能够泛解析cron表达式的执行时间,特别方便spa
控制台打印以下:code
hi! time is :2017-08-22 22:40:08 hello! time is :2017-08-22 22:40:09 hi! time is :2017-08-22 22:40:10 hello! time is :2017-08-22 22:40:11 hi! time is :2017-08-22 22:40:12 hello! time is :2017-08-22 22:40:13 hi! time is :2017-08-22 22:40:14 hello! time is :2017-08-22 22:40:15 hi! time is :2017-08-22 22:40:16 hello! time is :2017-08-22 22:40:17 hi! time is :2017-08-22 22:40:18 hello! time is :2017-08-22 22:40:19 hi! time is :2017-08-22 22:40:20 hello! time is :2017-08-22 22:40:21 hi! time is :2017-08-22 22:40:22 hello! time is :2017-08-22 22:40:23 hi! time is :2017-08-22 22:40:24
hello和hi交替执行,由于咱们配置的cron表达式是:sayHi方法从0秒开始,每两秒执行一次;sayHello方法从1秒开始,每两秒执行一次。orm
到此,咱们的定时任务运行成功!get