1.定時時間固定,只能在后台代碼更改
@Configuration @EnableScheduling public class ScheduleTask { @Autowired private UploadServiceImpl uploadServiceImpl; //添加定時任務,寫死時間 @Scheduled(cron = "0 */1 * * * ?") private void configureTasks() { uploadServiceImpl.putLocalFile(); //任務內容 } }
2.在數據庫獲取定時時間
2.1 建表
DROP TABLE IF EXISTS `cron`; CREATE TABLE `cron` ( `cron_id` varchar(30) NOT NULL PRIMARY KEY, `cron` varchar(30) NOT NULL ); INSERT INTO `cron` VALUES ('1', '0/5 * * * * ?'); select cron from cron limit 1;
2.2 后台代碼
@Configuration @EnableScheduling public class ScheduleTask implements SchedulingConfigurer { //獲取數據庫定時時間 @Autowired private UploadServiceImpl uploadServiceImpl; //添加定時任務,寫死時間 @Scheduled(cron = "0 */1 * * * ?") private void configureTasks() { uploadServiceImpl.putLocalFile(); //任務內容 } //添加定時任務,數據庫可修改時間格式 @Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { scheduledTaskRegistrar.addTriggerTask( //1.添加任務內容(Runnable) () -> uploadServiceImpl.putLocalFile(), //2.設置執行周期(Trigger) triggerContext -> { //2.1 從數據庫獲取執行周期 String cron = uploadServiceImpl.getCron(); //2.2 合法性校驗. if (StringUtils.isEmpty(cron)) { throw new RuntimeException("定時格式錯誤"); } //2.3 返回執行周期(Date) return new CronTrigger(cron).nextExecutionTime(triggerContext); } ); } }