本文转载至:http://www.cnblogs.com/java-zhao/p/5689592.html
1、application.properties
#\u5B9A\u65F6\u4EFB\u52A1
job.everysecond.cron=0/1 * * * * *
job.everytensecond.cron=0/10 * * * * *
job.everyminute.cron=0 0/1 * * * *
job.everysecond2.cron=* 0/1 * * * *
注意:cron表达式
- 第一个:每秒
- 第二个:每10秒
- 第三个:每分
- 第四个:每秒(注意这个不是每分)
package com.zzg.springbootone.cron;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* cron测试
*/
//@Configuration
@Component
public class CronJob {
int i = 0;
@Scheduled(cron = "${job.everysecond.cron}")
public void everySecond() {
System.out.println("第" + (++i) + "次调用,每秒任务,当前时间:" + nowTime());
}
private String nowTime() {
SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(new Date());
}
}
3、Application.java(启动类)
此时,启动boot,你会发现,定时任务并不会执行,还需添加一个注解。如下:
package com.zzg.springbootone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication //same as @Configuration+@EnableAutoConfiguration+@ComponentScan
@EnableSwagger2 //启动swagger注解
@EnableScheduling //启动定时任务
public class Application {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(Application.class, args);
}
}
注意:一定要在启动类上添加@EnableScheduling来启动定时任务,否则定时任务不会起作用!!!
测试:
启动服务,查看console的输出!!!