You can dynamically change the value of a cron expression without restarting the app
Import Java.util.date;import Org.slf4j.logger;import org.slf4j.loggerfactory;import Org.springframework.context.annotation.lazy;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; @Lazy (false) @Component @enablescheduling Public classDynamicscheduledtask implements Schedulingconfigurer {/** * by automatic injection start task Scheduling * * @Autowired * dynamicscheduledtask dynamicscheduledtask; * */ PrivateFinal Logger Logger = Loggerfactory.getlogger ( This. GetClass ()); Private StaticFinal String Default_cron ="0 0/10 * * *?"; PrivateString cron =Default_cron; /** * Get task Execution rules * @return*/ PublicString Getcron () {returnCron; } /** * Set task Execution rules * @param cron*/ Public voidSetcron (String cron) { This. Cron =Cron; } @Override Public voidconfiguretasks (Scheduledtaskregistrar taskregistrar) {taskregistrar.addtriggertask (NewRunnable () {@Override Public voidrun () {//Task LogicLogger.debug ("Dynamiccrontask is running ..."); } }, NewTrigger () {@Override PublicDate nextexecutiontime (Triggercontext triggercontext) {//task trigger, can modify the task's execution cycleCrontrigger trigger =NewCrontrigger (cron); Date nextexec=Trigger.nextexecutiontime (Triggercontext); returnnextexec; } }); }}
Spring annotation @Scheduled (cron = "0 0/10 * * * *?") Task scheduling dynamic Change Time