如何在特定CommandLineRunner之后运行计划任务?

时间:2018-03-28 16:00:44

标签: spring spring-boot

我在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()

2 个答案:

答案 0 :(得分:0)

1)添加@EnableScheduling

@EnableScheduling
@SpringBootApplication
public class MyCommandLineRunner implements CommandLineRunner {
...
}

2)用@Component

表示Spring Boot应用程序是没有意义的

<强>已更新

可以手动实现。提供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();
    }

}