Springboot 通过ThreadPoolTaskScheduler实现定时任务动态增、删、改

Springboot 通过Schedule实现定时任务动态增、删、改、启动、暂停

缺点:1、不支持分布式  (关于分布式任务调度会选择xxl-job或elasticjob,  xxl-job:https://www.xuxueli.com/xxl-job)

           2、本人未做界面开发,但是Controller层全部都已经定义好。

由于代码太多,值粘出部分代码,大家可以下载项目源码看看

数据库

CREATE TABLE `schedule_setting` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`job_name` varchar(255) DEFAULT NULL,
`class_name` varchar(255) DEFAULT NULL,
`method` varchar(255) DEFAULT NULL,
`cron` varchar(255) DEFAULT NULL,
`status` int(2) DEFAULT NULL COMMENT '0 代表开启,1代表关闭',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

 

Controller层

 

@RestController
@RequestMapping("/timmer")
public class TimmerController {

@Autowired
private TimmerServiceImpl timmerServiceImpl;

/**
* 添加任务
* @return
*/
@GetMapping("/add")
public ReponseData addTask(){
ReponseData res = new ReponseData();
try {
timmerServiceImpl.addTask();
res.setCode(0);
res.setMsg("添加成功");
} catch (Exception e){
res.setCode(1);
res.setMsg("添加失败");
}
return res;
}

/**
* 修改任务
* @return
*/
@GetMapping("/update")
public ReponseData updateTask(){
ReponseData res = new ReponseData();
try {
timmerServiceImpl.updateTask();
res.setCode(0);
res.setMsg("修改成功");
} catch (Exception e){
System.out.println(e.toString());
res.setCode(1);
res.setMsg("修改失败");
}
return res;
}

/**
* 暂停任务
*/
@GetMapping("/pause")
public ReponseData pauseTask(){
ReponseData res = new ReponseData();
try {
timmerServiceImpl.pauseTask();
res.setCode(0);
res.setMsg("暂停成功");
} catch (Exception e){
res.setCode(1);
res.setMsg("暂停失败");
}
return res;
}

/**
* 开启任务
*/
@GetMapping("/start")
public ReponseData startTask(){
ReponseData res = new ReponseData();
try {
timmerServiceImpl.startTask();
res.setCode(0);
res.setMsg("开启成功");
} catch (Exception e){
res.setCode(1);
res.setMsg("开启失败");
}
return res;
}


/**
* 删除任务
*/
@GetMapping("/del")
public ReponseData delTask(){
ReponseData res = new ReponseData();
try {
timmerServiceImpl.deleteTask();
res.setCode(0);
res.setMsg("删除成功");
} catch (Exception e){
res.setCode(1);
res.setMsg("删除失败");
}
return res;
}
}

 

定时任务核心

@Component
public class TimmerComponent {

// 保存任务
private Map> futuresMap = new ConcurrentHashMap>();

@Autowired
private TimmerDao timmerDao;

// 创建ThreadPoolTaskScheduler线程池
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(10);
return threadPoolTaskScheduler;
}

// 初始化任务
@Bean
public void initTimmer(){
List list = timmerDao.getScheduleList();
for (ScheduleConfig s : list){
ScheduledFuture future = threadPoolTaskScheduler.schedule(getRunnable(s), getTrigger(s));
futuresMap.put(s.getJobName(), future);
}
}

/**
* 添加任务
* @param s
*/
public void addTask(ScheduleConfig s){
ScheduledFuture future = threadPoolTaskScheduler.schedule(getRunnable(s), getTrigger(s));
futuresMap.put(s.getJobName(), future);
}

/**
* 暂停任务
* @param key
* @return
*/
public boolean pauseeTask(String key) {
ScheduledFuture toBeRemovedFuture = futuresMap.remove(key);
if (toBeRemovedFuture != null) {
toBeRemovedFuture.cancel(true);
return true;
} else {
return false;
}
}

/**
* 更新任务
* @param s
*/
public void updateTask(ScheduleConfig s) {
ScheduledFuture toBeRemovedFuture = futuresMap.remove(s.getJobName());
if (toBeRemovedFuture != null) {
toBeRemovedFuture.cancel(true);
}
addTask(s);
}


/**
* 转换首字母小写
*
* @param str
* @return
*/
public static String lowerFirstCapse(String str) {
char[] chars = str.toCharArray();
chars[0] += 32;
return String.valueOf(chars);
}

/**
* runnable
* @param scheduleConfig
* @return
*/
private Runnable getRunnable(ScheduleConfig scheduleConfig){
return new Runnable() {
@Override
public void run() {
Class clazz;
try {
clazz = Class.forName(scheduleConfig.getClassName());
String className = lowerFirstCapse(clazz.getSimpleName());
Object bean = (Object) ApplicationContextHelper.getBean(className);
Method method = ReflectionUtils.findMethod(bean.getClass(), scheduleConfig.getMethod());
ReflectionUtils.invokeMethod(method, bean);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
};
}

/**
* Trigger
* @param scheduleConfig
* @return
*/
private Trigger getTrigger(ScheduleConfig scheduleConfig){
return new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
CronTrigger trigger = new CronTrigger(scheduleConfig.getCron());
Date nextExec = trigger.nextExecutionTime(triggerContext);
return nextExec;
}
};

}
}

 


————————————————
原文链接:https://blog.csdn.net/xcc_2269861428/article/details/100023788

你可能感兴趣的:(Springboot 通过ThreadPoolTaskScheduler实现定时任务动态增、删、改)