1. 新建工程
新建一个普通的springboot工程,在启动类的上方加上@EnableScheduling,表示开启定时任务
package com.eknaij.schedulingtasks;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SchedulingtasksApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingtasksApplication.class, args);
}
}
2. 新建定时任务
每过一秒就在控制台输出当前时间
package com.eknaij.schedulingtasks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class SchedulingTask {
private static final Logger log = LoggerFactory.getLogger(ScheduledTask.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 1000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
}
通过在方法上加@Scheduled注解,表明该方法是一个调度任务。
@Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
@Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
@Scheduled(cron=" 1 * * * * ? * ") :通过cron表达式定义规则,什么是cro表达式,自行搜索引擎。
在线Cron表达式生成器
执行效果:
3. 总结
springboot下开启定时任务主要有两个要点:
- 在启动类加上@EnableScheduling注解
- 给方法添加时限