在 spring 引导应用程序中从数据库加载 Cron 语法

Load Cron syntax from database in spring boot application

这是我的计划任务class

@Component
public class ScheduledTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledTask.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(cron = "${scheduling.job.cron}")
    public void reportCurrentTime() {
        LOGGER.info("The time is now {}", dateFormat.format(new Date()));
    }
}

目前,我正在从 application.properties 文件加载 cronjob 语法。但是我想在 Spring 引导应用程序开始时从 SQL 数据库加载 cron 语法。这是我的数据库脚本,它具有 cronjob 语法

CREATE TABLE tbl_configuration_details 
(
config_id int NOT NULL, 
schedule_time int NOT NULL,
schedule_time_format nvarchar(10) NOT NULL,
data_ttl int NOT NULL,
data_ttl_format nvarchar(10) NOT NULL,
cron_job_syntax nvarchar(255) NOT NULL,
created_timestamp datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_by int NOT NULL,
modified_timestamp datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
modified_by int NOT NULL,
PRIMARY KEY (config_id)
);

第 1 步:创建 bean 以从数据库中获取 cron 语法

@Bean
public String getCronSyntax() {
    AppConfiguration appConfiguration = configurationService.getConfiguration();
    String cronSyntax = appConfiguration.getCronJobSyntax();
    LOGGER.info("cronsyntax: " + cronSyntax);
    return cronSyntax;
}

第 2 步:在 Schedule 注释中使用 # 从 cron 语法获取 bean 值

@Scheduled(cron = "#{getCronSyntax}")
private void cronSchedule() {
     LOGGER.info("The time is now {}", dateFormat.format(new Date()));
}