2016-05-09 12 views
4

我正在使用Spring Boot,并且在使用数据库中存在的值时调度cron task时出现问题。Spring Boot:从数据库获取@Scheduled cron值

暂且,我在读从属性值文件象下面这样:

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

这工作得很好,但而不是获取值从属性文件,我想从数据库表中得到它们。这是可能的和如何?

+0

因为春天也没关系,其中属性来自何方,文件,数据库,混帐只要他们到底是属性。 –

+1

我试图实现一个方法,该方法从数据库中提取字符串值,并尝试在@Scheduled中注入此字符串,但它表示:注释属性Scheduled.cron的值必须是常量表达式 – Daniel

+0

您不需要更改任何'@ Scheduled'只需要从数据库中检索属性并将它们传递给'context:property-placeholder',或者如果你使用java配置文件,则使用'ApplicationContextInitializer'来添加'PropertySource'来执行相同的操作。 –

回答

0

要实现您的目标,您必须在运行时配置您的调度程序。这意味着你需要使用更多的低级调度器API。准确地说,当您已经准备好连接数据库时,您可以配置您的调度程序。我认为你需要摆脱使用@Scheduled注释和manully管理你的调度。

我认为这些主题可以帮助来形容我的意思是:

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

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

但是总是可以用野生的方法,你会拦截豆创建并使用自定义元数据替换注释上的原始注释,但为了实现它,您必须知道许多框架k细节以及@Scheduled annatation处理器如何工作。

1

您需要从存储值的数据库表中加载属性。 和合并与应用性能

@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; 
    } 

如需更多帮助,DB属性是指https://analyzejava.wordpress.com/2015/01/16/loading-configuration-properties-from-database-in-spring-based-application/