编写定时执行器代码,注意当定时器如果在动态更新的时候,cron表达式如果写出,就会造成执行器不能正常执行,第二种情况是,如果设置的cron表达式需要执行才能执行到更新的cron表达式值,如果设置的cron表达式时长很久才执行,那就很难执行到新设置的cron值,所以推荐使用quartz或者xxl-job,所以更新的cron表达式一定要严格规范
package com.demo.scheduling;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;
@Data
@Slf4j
@Component
@EnableScheduling
public class ScheduleTask implements SchedulingConfigurer {
@Value("${order.cron}")
private String cron;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(() ->
log.info("Current time: {}", LocalDateTime.now()), new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
CronTrigger cronTrigger = new CronTrigger(cron);
Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);
return nextExecutionTime;
}
});
}
}
修改cron表达式请求
package com.huan.study.mybatis.scheduling;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
private final ScheduleTask scheduleTask;
@Autowired
public TestController(ScheduleTask scheduleTask) {
this.scheduleTask = scheduleTask;
}
@GetMapping("/updateCron")
public String updateCron(String cron) {
log.info("new cron :{}", cron);
scheduleTask.setCron(cron);
return "修改成功";
}
}