Spring Boot : Getting @Scheduled cron value from d

2020-06-01 08:42发布

问题:

I'm using Spring Boot and have issues scheduling a cron task using values existing in database.

For the time being, I'm reading values from properties file like below :

@Scheduled(cron= "${time.export.cron}")
public void performJob() throws Exception {
   // do something
}

This works nicely, but instead of getting values from properties file, I want to get them from database table. Is it possible and how ?

回答1:

you can add a bean to get cron value from database in the SpringBootApplication main class or in any of the configuration class. Example code is below:

@Autowired
private CronRepository cronRepo;

@Bean
public int getCronValue()
{
    return cronRepo.findOne("cron").getCronValue();
}

you should create a table and provide suitable values in the database. After that you can provide the bean inside the @Scheduled. Example code is below:

@Scheduled(cron="#{@getCronValue}")

Hope it works for your issue.



回答2:

To achieve your goals you must configure your scheduler at runtime. It means you need to use more low-level scheduler API. Precisely when you have already prepared connect with your database you can configure your scheduler. I think you need to get rid of using @Scheduled annotation and manully manage your scheduler.

I think these topics can help to describe what I mean:

  1. How to change Spring's @Scheduled fixedDelay at runtime

  2. Scheduling a job with Spring programmatically (with fixedRate set dynamically)

However always you can use wild approaches where you would intercept the bean creation and replace original annotation on annotation with custom metadata but in order to implement it you must know many framework details and how @Scheduled annatation processor works.



回答3:

You need to load properties from the database table in which your value stored. and merge that db properties with application properties

    @Autowired
    private DataSource dataSource;

    @Autowired
    private DatabaseConfiguration configuration;

    @Bean(name = "propertyConfig")
    public DatabaseConfiguration getDatabaseConfiguration() {
        DatabaseConfiguration configuration = new DatabaseConfiguration(dataSource, "propertyTable", "key", "value");
        return configuration;
    }

    @Bean(name = "dbProperty")
    public Properties getDBProperties(){
        Properties properties = ConfigurationConverter.getProperties(configuration);
        return properties;
    }

For more help refer https://analyzejava.wordpress.com/2015/01/16/loading-configuration-properties-from-database-in-spring-based-application/



回答4:

Using @Bean annotated method will do the trick. But as SpringBoot only going to call this method 1 time, and return cached version after that, you will need to restart Spring to getting new value.

To get new run time from database, using SchedulingConfigurer:

@Configuration
public class SchedulerConfig implements SchedulingConfigurer {

    @Autowired
    private YourService yourService;

    @Bean
    public YourJob yourJob() {
        return new YourJob();
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                () -> yourJob().performJob(),
                (TriggerContext triggerContext) -> yourService.getCron()
        );
    }

}

Note: don't use @Scheduled with this way.