注解方式和接口方式,是可以在一个项目中共存的。
基于注解的方式
- 在启动类上,开启定时任务功能(加上@EnableScheduling注解):
@EnableScheduling
@SpringBootApplication
@ComponentScan({ "com.boco.fyk.timer.**" })
public class TimerApplication {
public static void main(String[] args) {
SpringApplication.run(TimerApplication.class, args);
}
}
- 编写定时任务类:
@Component
@Slf4j
public class Test {
@Async
@Scheduled(fixedDelay = 10000)
public void handle() {
log.info("fixedDelay-每间隔多少毫秒执行一次(这个时间间隔是:最后一次调用结束和下一次调用开始之间)!");
}
@Async
@Scheduled(fixedRate = 10000)
public void handle2() {
log.info("fixedRate-每间隔多少毫秒执行一次!");
}
@Async
@Scheduled(cron = "0/10 * * * * *")
public void handle3() {
log.info("cron-cron表达式配置执行时间,不支持年");
}
}
需要注意的是,定时任务默认是以单线程来执行的。所以,可能出现一个问题,就是定时任务在执行的过程中,发生了异常,那么定时任务就不会再执行了。因此,这里要使用多线程来执行这个定时任务。
这里:
- @Component:表示要将这个类,交由spring管理;
- @Async:表示开启多线程来执行方法;(SpringBoot中多线程的使用,见:异步任务(多线程))
- @Scheduled:定时任务的时间配置;
基于接口的方式
基于注解的方式很简单,但是也存在一个问题,那就是执行周期的时间,无法动态改变。也就是说,要调整执行周期,只有重启任务。
要实现动态改变执行周期,可以使用接口的方式:
- 同注解方式一样,先要开启定时任务:
@EnableScheduling
@SpringBootApplication
@ComponentScan({ "com.boco.fyk.timer.**" })
public class TimerApplication {
public static void main(String[] args) {
SpringApplication.run(TimerApplication.class, args);
}
}
- 实现接口:
@Component
@Slf4j
public class DynamicScheduleTask implements SchedulingConfigurer {
/**
* 执行定时任务.
*/
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(() -> (new CustomTask()).doThings(),
triggerContext -> new CronTrigger("0/10 * * * * *").nextExecutionTime(triggerContext));
}
class CustomTask {
public void doThings() {
log.info("执行了一个自定义定时任务");
}
}
}
这里,作为示例,是把时间写死了,实际情况,可以从数据库或其他地方获取。
另外new CronTrigger(“0/10 * * * * *”).nextExecutionTime(triggerContext))
代码,会在每次定时任务都会重新执行这个代码,所以,这里可以换成其他语句,获取到具体的定时任务值。