This is my Scheduled task 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()));
}
}
Currently, I am loading cronjob syntax from application.properties file. But I want to load cron syntax from SQL database at the start of Spring boot application. Here is my database script which is having cronjob syntax
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)
);
Step 1: Create bean to fetch cron syntax from databse
@Bean
public String getCronSyntax() {
AppConfiguration appConfiguration = configurationService.getConfiguration();
String cronSyntax = appConfiguration.getCronJobSyntax();
LOGGER.info("cronsyntax: " + cronSyntax);
return cronSyntax;
}
Step 2: Use # to get bean value form cron syntax in Schedule annotation
@Scheduled(cron = "#{getCronSyntax}")
private void cronSchedule() {
LOGGER.info("The time is now {}", dateFormat.format(new Date()));
}