实现SchedulingConfigurer接口,并且重写configureTasks方法。
demo1
package cn.biz.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
/**
* @Description 可动态更改时间的定时任务
* @Author
* @Date 2021/3/2
* @Version 1.0.0
*/
@Component
public class SchedulingTask implements SchedulingConfigurer {
private final Logger logger = LoggerFactory.getLogger(SchedulingTask .class);
// cron表达式,我们动态更改此属性的值即可更改定时任务的执行时间
private String expression = "0 0/2 * * * ?";
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
// 定时任务要执行的方法
Runnable task = () -> {
//业务逻辑
logger.info(">>> configureTasks-----------【"+expression+"】");
};
// 调度实现的时间控制
Trigger trigger = triggerContext -> {
CronTrigger cronTrigger = new CronTrigger(expression);
return cronTrigger.nextExecutionTime(triggerContext);
};
taskRegistrar.addTriggerTask(task, trigger);
}
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
}
编写一个接口进行调用,动态改变定时任务的时间
package com.nobody.controller;
import cn.biz.impl.SchedulingTask;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Autowired
private SchedulingTask schedulingTask;
/**
* @Description
* @Author Mr.nobody
* @Date 2021/3/2
* @Version 1.0.0
*/
@RestController
@RequestMapping("demo")
public class DemoController {
@ResponseBody
@PostMapping("/changeCron")
public String ChangeTimeScheduledTask() {
String cronExpression= getDictionaryValue("cronExpression", "Dictionary");//取字典配置定时任务表达式;
if(StringUtils.isNoneBlank(cronExpression)){schedulingTask.setExpression(cronExpression);}
return "changeCron ok";
}
}
demo1升级版:
分布式环境 可以增加zk分布式锁,防止集群定时任务重复执行
package cn.biz.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
/**
* @Description 可动态更改时间的定时任务
* @Author
* @Date 2021/3/2
* @Version 1.0.0
*/
@Component
public class SchedulingTask implements SchedulingConfigurer {
private final Logger logger = LoggerFactory.getLogger(SchedulingTask .class);
// cron表达式,我们动态更改此属性的值即可更改定时任务的执行时间
private String expression = "0 0/2 * * * ?";
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
// 定时任务要执行的方法
Runnable task = () -> {
//1、重试策略:初试时间为1s 重试3次
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//2、通过工厂创建连接
CuratorFramework client = CuratorFrameworkFactory.newClient(zkAddress, retryPolicy);
//3、开启连接
client.start();
//4、获取zk分布式锁
InterProcessMutex mutex = new InterProcessMutex(client, "/curator/lock");
boolean flag = false;
try {
//尝试获取锁,最多等待0秒
flag = mutex.acquire(0, TimeUnit.SECONDS);
Thread currentThread = Thread.currentThread();
if(flag){//锁抢占成功 执行业务逻辑
logger.info(">>> configureTasks-----------【"+expression+"】");
//开始业务逻辑
}
//
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
} finally{
if(flag){
//1.先释放锁
if(flag){
try {
mutex.release();
} catch (Exception e) {
e.printStackTrace();
}
}
//2.后关闭zk客户端连接
if (client != null) {
client.close();
}
}
}
};
// 调度实现的时间控制
Trigger trigger = triggerContext -> {
CronTrigger cronTrigger = new CronTrigger(expression);
return cronTrigger.nextExecutionTime(triggerContext);
};
taskRegistrar.addTriggerTask(task, trigger);
}
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
}
https://www.cnblogs.com/luciochn/p/14474485.html
springboot 定时任务 实现SchedulingConfigurer接口,修改定时任务不重启项目