我在CommandLineRunner的run
函数中做了一些初始化,我希望我的Scheduled
任务在初始化后开始计划,我该如何实现呢?
例如,我有CommandLineRunner:
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// Initializations
// ...
}
}
任务调度程序:
public class SchedClass {
@Scheduled(fixedRate = ONE_SECOND)
public void sched() {
}
}
如何在sched()
运行后运行run()
?
答案 0 :(得分:0)
1)添加@EnableScheduling
@EnableScheduling
@SpringBootApplication
public class MyCommandLineRunner implements CommandLineRunner {
...
}
2)用@Component
<强>已更新强>
可以手动实现。提供TaskScheduler
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(5);
threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
return threadPoolTaskScheduler;
}
将其与MyCommandLineRunner
一起注入SchedClass
并运行
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Autowired
private ThreadPoolTaskScheduler taskScheduler;
@Autowired
private SchedClass schedBean;
@Override
public void run(String... args) throws Exception {
// ...
taskScheduler.scheduleWithFixedDelay(() -> schedBean.sched(), ONE_SECOND);
// ...
}
}
答案 1 :(得分:0)
class MySchedulingConfigurer implements SchedulingConfigurer {
private ScheduledTaskRegistrar taskRegistrar;
private IntervalTask task;
public MySchedulingConfigurer(IntervalTask task) {
this.task = task;
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
this.taskRegistrar = taskRegistrar;
}
public void resume() {
this.taskRegistrar.scheduleFixedRateTask(task);
}
}
@Configuration
class SchedulerConfiguration {
@Autowired
private MySchedulingConfigurer schedulingConfigurer;
@Bean
public MySchedulingConfigurer mySchedulingConfigurer() {
IntervalTask task = new IntervalTask(new MyTask(), 5000L);
return new MySchedulingConfigurer(task);
}
public static class MyTask implements Runnable {
@Override
public void run() {
System.out.println("===> task executed...");
}
}
@EventListener
public void startScheduler(ApplicationReadyEvent event){
schedulingConfigurer.resume();
}
}
@Component
class CacheLoadingRunner implements CommandLineRunner {
@Autowired
private MySchedulingConfigurer schedulingConfigurer;
@Override
public void run(String... args) throws Exception {
schedulingConfigurer.resume();
}
}