使用来自 yaml 文件的多个 cron 表达式 Spring-Boot 一个 @Scheduled 任务 [英] Spring-Boot one @Scheduled task using multiple cron expressions from yaml file

查看:32
本文介绍了使用来自 yaml 文件的多个 cron 表达式 Spring-Boot 一个 @Scheduled 任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢使用 .yml 文件的不同配置属性来实现一个 @Scheduled 作业.

I like to have an implementation of one @Scheduled job using different configuration properties of .ymlfile.

意味着在我的 yaml 文件中,我将 cron 表达式 描述为一个列表:

Means in my yaml file I describe the cron expression as a list:

job:
  schedules:
  - 10 * * * * *
  - 20 * * * * *

我使用 Configuration 读出这些值并创建了一个名为 scheduled@Bean:

I read those values out using Configuration and created a @Bean named scheduled:

@Configuration
@ConfigurationProperties(prefix="job", locations = "classpath:cronjob.yml")
public class CronConfig {

    private List<String> schedules;

    @Bean
    public List<String> schedules() {
        return this.schedules;
    }

    public List<String> getSchedules() {
        return schedules;
    }

    public void setSchedules(List<String> schedules) {
        this.schedules = schedules;
    }
}

在我的 Job 类中,我想开始执行一种方法,但要针对我的配置中的两个计划.

In my Job class I want to start the execution of one method but for both of the schedules in my configuration.

 @Scheduled(cron = "#{@schedules}")
 public String execute() {
     System.out.println(converterService.test());
     return "success";
 }

使用此解决方案,应用程序会产生错误:(或多或少清楚)

With this solution the application creates an error: (more or less clear)

Encountered invalid @Scheduled method 'execute': Cron expression must consist of 6 fields (found 12 in "[10 * * * * *, 20 * * * * *]")

有没有办法用多个 cron 表达式声明来配置相同的调度作业方法?

编辑 1

经过一些尝试,我只是在执行程序方法上使用了第二个注释.

After some try I just used a second annotation on the executer method.

@Scheduled(cron = "#{@schedules[0]}")
@Scheduled(cron = "#{@schedules[1]}")
public String execute() {
    System.out.println(converterService.test());
    return "success";
}

此解决方案有效但不是真正动态的.有没有办法让这个动态?

This solution works but is not really dynamic. Is there also a way to make this dynamic?

推荐答案

(编辑,因为我找到了执行此操作的方法)

你实际上可以做到这一点.下面我展示了一个工作示例:

You can actually do this. Below I'm showcasing a working example:

cronjob.yaml

job:
  schedules:
  - 10 * * * * *
  - 20 * * * * *

要执行的实际任务MyTask:

package hello;

import org.springframework.stereotype.Component;

@Component
public class MyTask implements Runnable {

    @Override
    public void run() {
        //complicated stuff
    }
}

您的 CronConfig 原样:

package hello;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

    @Configuration
    @ConfigurationProperties(prefix="job", locations = "classpath:cronjob.yml")
    public class CronConfig {

        private List<String> schedules;

        @Bean
        public List<String> schedules() {
            return this.schedules;
        }

        public List<String> getSchedules() {
            return schedules;
        }

        public void setSchedules(List<String> schedules) {
            this.schedules = schedules;
        }
    }

负责调度所有 cron 的 ScheduledTask bean:

The ScheduledTask bean that is responsible to schedule all crons:

package hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

    @Autowired
    private TaskScheduler taskScheduler;

    @Autowired
    private CronConfig cronConfig;

    @Autowired
    private MyTask myTask;

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    public void scheduleAllCrons() {

        cronConfig.getSchedules().forEach( cron -> taskScheduler.schedule(myTask, new CronTrigger(cron)) );
    }
}

上下文/主类应用:

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class Application {

    @Bean
    public TaskScheduler taskScheduler() {
        return new ConcurrentTaskScheduler();
    }


    public static void main(String[] args) throws Exception {
        ApplicationContext ctx = SpringApplication.run(Application.class);

        ScheduledTasks scheduledTasks = ctx.getBean(ScheduledTasks.class);

        scheduledTasks.scheduleAllCrons();
    }
}

这篇关于使用来自 yaml 文件的多个 cron 表达式 Spring-Boot 一个 @Scheduled 任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆