如何在不使用@Scheduled()批注的情况下在春季启动中安排cron作业

时间:2019-07-08 15:26:19

标签: spring spring-boot cron job-scheduling spring-scheduled

在Spring Boot中,我可以通过不对方法使用@Scheduled注释来安排Spring作业吗?

我正在春季靴中从事春季工作。我想使用cron表达式来计划作业,但不对方法使用@Scheduled(cron =“”)注释。

我知道我可以按照以下方法安排工作。

@计划的(cron =“ 0 10 10 10 *?”)

public void execute(){

/ *一些工作代码* /

}

但是我希望它是动态的,以便我可以将cron表达式用作用户的输入并安排它。

2 个答案:

答案 0 :(得分:0)

我想出了一个可行的示例,因为我发现您的问题很有趣,并且之前对此问题一直很感兴趣。它完全基于源代码,因此我不知道它是否接近遵循最佳实践。尽管如此,您仍然可以根据需要进行调整。仅供参考,您不一定需要创建一个新的ScheduledTaskRegistrar对象-我认为由于您的目标是动态调度程序,因此您对仅使用覆盖方法定义任务就不会有兴趣。

@SpringBootApplication
public class TaskScheduler implements SchedulingConfigurer, CommandLineRunner {

    public static void main(String[] args){SpringApplication.run(TaskScheduler.class, args);}

    List<CronTask> cronTasks;

    @Override
    public void run(String... args) throws Exception {
        CronTask task = this.createCronTask(new Runnable() {
            @Override
            public void run() {
                System.out.println(LocalDateTime.now());
            }
        }, "1/10 * * * * *");

        ScheduledTaskRegistrar taskRegistrar = new ScheduledTaskRegistrar();
        taskRegistrar.addCronTask(task);
        configureTasks(taskRegistrar);
        Thread.sleep(51);

        taskRegistrar.destroy();
        taskRegistrar = null;

        ScheduledTaskRegistrar taskRegistrar2 = new ScheduledTaskRegistrar();
        taskRegistrar2.addCronTask(task);
        configureTasks(taskRegistrar2);

    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // "Calls scheduleTasks() at bean construction time" - docs
        taskRegistrar.afterPropertiesSet();
    }

    public CronTask createCronTask(Runnable action, String expression) {
        return new CronTask(action, new CronTrigger(expression));
    }

}

我有在Azure和其他地方使用cron作业的经验。在Java编程中,为了简化起见,我通常使用固定时间的@Scheduled。希望这对您有用。

答案 1 :(得分:-1)

这是我的工作示例,如果有人想使用TaskScheduler而不使用@Scheduled Annotation

@配置类

@Configuration
public class SchedulerConfig implements SchedulingConfigurer {

    final Logger LOGGER = LogManager.getLogger(SchedulerConfig.class);

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        LOGGER.debug("Creating Async Task Scheduler");
        scheduledTaskRegistrar.setTaskScheduler(taskScheduler());
    }

    // This is mandatory otherwise it will to be able to find bean of       
    // taskScheduler. Without this it was giving runtime error says, can not find 
    // taskScheduler bean.
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(20); // Better to read it from property file.
        scheduler.setThreadNamePrefix("ThreadScheduler-");
        scheduler.initialize();
        return scheduler;
    }
}

计划程序类,从应用程序类中调用。


@Component
public class MyTaskScheduler {

    private TaskScheduler taskScheduler;
    // Here we are auto-wiring taskScheduler, that's why need to create 
   // taskScheduler bean in configuration class
    @Autowired
    public void setScheduler(TaskScheduler scheduler) {
        this.taskScheduler = scheduler;
    }

    public void schedule() {
        taskScheduler.scheduleWithFixedDelay(new Runnable(){
            @Override
            public void run() {
                System.out.println("I am running after every 1 second");
            }
        }, 1000);
    }
}

如果@Configuration注释不起作用,请将@EnableConfigurationProperties放在主要运行类中。 确保将@EnableScheduling放在Application类中,以便主可运行类看起来像

@SpringBootApplication
@EnableScheduling
@EnableConfigurationProperties
public class MainApplication implements CommandLineRunner {

    @Autowired
    MyTaskScheduler myTaskScheduler;

    public static void main(String[] args) {
        final Logger logger = LogManager.getLogger(MainApplication.class);
        SpringApplication.run(MainApplication.class, args);
        logger.info("Application started");
    }

    @Override
    public void run(String... args) throws Exception {
        myTaskScheduler.schedule();
    }
}