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表达式
- 第一个:每秒
- 第二个:每10秒
- 第三个:每分
- 第四个:每秒(注意这个不是每分)
2、CronJobTest.java
package com.xxx.secondboot.cron; import java.util.Date; import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; /**
* cron测试
*/
//@Configuration
@Component
public class CronJobTest { int i = 0; @Scheduled(cron = "${job.everysecond.cron}")
public void everySecond() {
System.out.println("第" + (++i) + "次调用,每秒任务,当前时间:" + nowTime());
} private String nowTime() {
return DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
}
}
3、Application.java(启动类)
此时,启动boot,你会发现,定时任务并不会执行,还需添加一个注解。如下:
package com.xxx.secondboot; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication
@EnableSwagger2
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
注意:一定要在启动类上添加@EnableScheduling来启动定时任务,否则定时任务不会起作用!!!
测试:
启动服务,查看console的输出!!!