背景
我们经常会碰到一些需要执行定时任务的场景,在SpringBoot中实现非常的简单,我们首先通过在配置类注解@EnableScheduling来开启计划任务的支持,然后在要执行计划任务的方法上注解@Scheduled来声明这是一个计划任务。
实例
计划任务执行类
@Service
public class ScheduledService {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
/**
* 上一个调用开始后再次调用的延时(不用等待上一次调用完成)
* 周期执行
*/
@Scheduled(fixedRate = 5000) //①
public void reportCurrentTime() {
System.out.println("每隔五秒执行一次 " + dateFormat.format(new Date()));
}
/**
* 配置时间的表达式, 比如下式的每天下午17:33执行
*/
@Scheduled(cron = "0 33 17 ? * *" ) //②
public void fixTimeExecution(){
System.out.println("在指定时间 " + dateFormat.format(new Date())+"执行");
}
}
上式子中有一个需要注意的是,关于@Scheduled 的属性fixedDelay和fixedRate比较:
- fixedRate:该属性的含义是上一个调用开始后再次调用的延时(不用等待上一次调用完成),这样就会存在重复执行的问题,所以不是建议使用,但数据量如果不大时在配置的间隔时间内可以执行完也是可以使用的。
- fixedDelay:该属性的功效与上面的fixedRate则是相反的,配置了该属性后会等到方法执行完成后延迟配置的时间再次执行该方法。
配置类
@Configuration
@ComponentScan("com.example.demo.test.schedule")
@EnableScheduling
public class TaskSchedulerConfig {
}
运行类
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
}
}
运行结果: