Springboot设置定时任务,从数据库中获取cron表达式 DEMO
适用场景:需要在项目运行时改动定时任务执行时间,可将cron表达式放在缓存或者数据库中
代码如下:(省略了获取cron的方法,需要自己根据情况获取)
import org.springframework.scheduling.Trigger; 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.LocalTime; import java.util.Date; /** * @ClassName: TaskDemo * @desc: * @authoer: demo * @create: 2022/6/17 13:56 */ @Component @EnableScheduling public class TaskDemo implements SchedulingConfigurer { public static String cron; @Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { //项目启动时候,会在这里执行一次,从数据库拿到数据库 cron = "0 0/1 * * * ?"; Runnable task = () -> { System.out.println("任务逻辑代码执行:" + LocalTime.now()); }; Trigger trigger = (triggerContext) -> { //任务触发 ,每次触发都会执行这里面的方法一次,重新获取下一次的更新时间 cron = "0 0/2 * * * ?"; CronTrigger cronTrigger = new CronTrigger(cron); Date nextExec = cronTrigger.nextExecutionTime(triggerContext); return nextExec; }; scheduledTaskRegistrar.addTriggerTask(task,trigger); }