SpringBoot动态修改定时任务cron参数

1.启动类Application添加@EnableScheduling注解:

@EnableScheduling
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2.动态定时任务类DynamicScheduleTaskSecond

package com.xzp.common;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import com.sgcc.bench.admin.cud.loginlog.services.ISgBenchLoginLogService;

@Component
public class DynamicScheduleTaskSecond implements SchedulingConfigurer {

    @Autowired
    private ISgBenchLoginLogService iSgBenchLoginLogService;
    // 配置文件读取
    @Value("${audit.schedule.cron}")
    private String cron;

    public String getCron() {
        return cron;
    }

    public void setCron(String cron) {
        this.cron = cron;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                try {
                                        //写自己定时要执行的任务
                    iSgBenchLoginLogService.sendmail();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Trigger() {

            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                System.out.println("-----------"+cron);
                if ("".equals(cron) || cron == null)
                    return null;
                CronTrigger trigger = new CronTrigger(cron);// 定时任务触发,可修改定时任务的执行周期
                Date nextExecDate = trigger.nextExecutionTime(triggerContext);
                return nextExecDate;
            }
        });
    }

}

3.控制器UserController

@Autowired
DynamicScheduleTaskSecond dynamicScheduleTaskSecond;

// 更新动态任务时间
@RequestMapping("/updateDynamicScheduledTask")
@ResponseBody
public AjaxResult updateDynamicScheduledTask() {
   //在需要动态修改定时任务cron参数的地方调用,此处只是示例
   dynamicScheduleTaskSecond .setCron("0/10 * * * * ?");
   return new AjaxResult().success();
}

你可能感兴趣的:(SpringBoot动态修改定时任务cron参数)