SpringBoot实现项目在运行时改变定时器运行时间

import com.qhkj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
 * 动态修改定时器时间
 *  *实现项目运行之后动态修改定时器时间
 *  步骤:
 *  1.类上添加注解@EnableScheduling
 *  2.实现 SchedulingConfigurer 接口
 * @Author: zgq
 * @Date: 2019/10/14 15:56
 * @DESC:
 */
@RestController
@EnableScheduling
public class CronChangeTime implements SchedulingConfigurer {
    Logger logger = LogManager.getLogger(TaskCronChange.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    //每5s执行一次
    private String expression = "0/5 * * * * *";
//    private String expression = null;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        Runnable task = new Runnable() {
            @Override
            public void run() {
			/**
			   *在这里写你需要定时运行的业务逻辑代码
			*/
                logger.info("run----"+dateFormat.format(new Date()));
            }
        };
        Trigger trigger =new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                CronTrigger cronTrigger = new CronTrigger(expression);
                return cronTrigger.nextExecutionTime(triggerContext);
            }
        };
        scheduledTaskRegistrar.addTriggerTask(task,trigger);
    }


    /** *
     *调用该方法将定时器的cron时间传入就可以了
     * @author zgq
     * @date 2019/10/14
     * @param
     * @return java.lang.String
     */
    @RequestMapping(value = "changeTime")
    public String changeExpression(String cron){
        expression = cron;
        return "changeTime";
    }
}

在线Cron表达式生成器

你可能感兴趣的:(修改定时器时间,SpringBoot学习)