一、依赖
org.springframework.boot spring-boot-starter
二、实现
启动类上需加上@EnableScheduling注解
SpringBootSchedulingApplication.java
package com.example.demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication@EnableSchedulingpublic class SpringBootSchedulingApplication { public static void main(String[] args) { SpringApplication.run(SpringBootSchedulingApplication.class, args); }}
Task1.java
package com.example.demo.utils.task;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;/** * 每隔六秒执行(cron表达式) * * @Author: 我爱大金子 * @Description: 每隔六秒执行(cron表达式) * @Date: Create in 18:03 2017/7/4 */@Componentpublic class Task1 { private int count=0; @Scheduled(cron="*/6 * * * * ?") private void process(){ System.out.println("this is scheduler task runing "+(count++)); }}
Task2.java
package com.example.demo.utils.task;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;import java.text.SimpleDateFormat;import java.util.Date;/** * 每隔六秒执行(fixed方式) * * @Author: 我爱大金子 * @Description: 每隔六秒执行(fixed方式) * @Date: Create in 18:03 2017/7/4 */@Componentpublic class Task2 { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 6000) public void reportCurrentTime() { System.out.println("现在时间:" + dateFormat.format(new Date())); }}
效果:
三、说明
3.1、@Scheduled参数
@Scheduled参数可以接受两种定时的设置:一种是我们常用的cron="*/6 * * * * ?",一种是 fixedRate = 6000,两种都表示每隔六秒打印一下内容。
fixedRate说明
@Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行
@Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行
@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次
3.2、Could not find default TaskScheduler bean异常处理
就会在debug级别的日志输出一个异常:
logger.debug("Could not find default TaskScheduler bean", ex);
当然,这个异常并不影响应用程序运行,如果你不想看到这个异常,就可以通过提升org.springframework.scheduling这个包下日志级别来屏蔽这个不合理的异常。