springcloud-定时任务

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


    }
原文地址:https://www.cnblogs.com/hyy9527/p/14931993.html