标签:
1、application.properties
#cron
job.everysecond.cron=0/1 * * * * *
job.everytensecond.cron=0/10 * * * * *
job.everyminute.cron=0 0/1 * * * *
job.everysecond2.cron=* 0/1 * * * *
注意:cron表达式
2、CronJobTest.java
1 package com.xxx.secondboot.cron; 2 3 import java.util.Date; 4 5 import org.apache.commons.lang3.time.DateFormatUtils; 6 import org.springframework.context.annotation.Configuration; 7 import org.springframework.scheduling.annotation.Scheduled; 8 import org.springframework.stereotype.Component; 9 10 /** 11 * cron测试 12 */ 13 //@Configuration 14 @Component 15 public class CronJobTest { 16 17 int i = 0; 18 19 @Scheduled(cron = "${job.everysecond.cron}") 20 public void everySecond() { 21 System.out.println("第" + (++i) + "次调用,每秒任务,当前时间:" + nowTime()); 22 } 23 24 private String nowTime() { 25 return DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"); 26 } 27 }
3、Application.java(启动类)
此时,启动boot,你会发现,定时任务并不会执行,还需添加一个注解。如下:
1 package com.xxx.secondboot; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 import org.springframework.scheduling.annotation.EnableScheduling; 6 7 import springfox.documentation.swagger2.annotations.EnableSwagger2; 8 9 @SpringBootApplication 10 @EnableSwagger2 11 @EnableScheduling 12 public class Application { 13 public static void main(String[] args) { 14 SpringApplication.run(Application.class, args); 15 } 16 }
注意:一定要在启动类上添加@EnableScheduling来启动定时任务,否则定时任务不会起作用!!!
测试:
启动服务,查看console的输出!!!
标签:
原文地址:http://www.cnblogs.com/java-zhao/p/5689592.html