Spring Boot : Getting @Scheduled cron value from database

42,140

Solution 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.

Solution 2

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/

Solution 3

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.

Share:
42,140
Daniel
Author by

Daniel

Updated on September 01, 2020

Comments

  • Daniel
    Daniel almost 4 years

    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 ?