Spring Boot 系列教程14-动态修改定时任务cron参数
动态修改定时任务cron参数
- 不需要重启应用就可以动态的改变Cron表达式的值
- 不能使用@Scheduled(cron = “${jobs.cron}”)实现
DynamicScheduledTask.java
package com.jege.spring.boot.task;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
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.jege.spring.boot.data.jpa.entity.User;
import com.jege.spring.boot.data.jpa.repository.UserRepository;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:动态修改定时任务cron参数
*/
@Component
public class DynamicScheduledTask implements SchedulingConfigurer {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
private static final String DEFAULT_CRON = "0/5 * * * * ?";
private String cron = DEFAULT_CRON;
@Autowired
private UserRepository userRepository;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
if (!cron.equals(DEFAULT_CRON)) {
User user = new User("je_ge", 20);
userRepository.save(user);
}
// 定时任务的业务逻辑
System.out.println("动态修改定时任务cron参数,当前时间:" + dateFormat.format(new Date()));
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
// 定时任务触发,可修改定时任务的执行周期
CronTrigger trigger = new CronTrigger(cron);
Date nextExecDate = trigger.nextExecutionTime(triggerContext);
return nextExecDate;
}
});
}
public void setCron(String cron) {
this.cron = cron;
}
}
Application.java
@EnableScheduling
UserController.java
@Autowired
DynamicScheduledTask dynamicScheduledTask;
// 更新动态任务时间
@RequestMapping("/updateDynamicScheduledTask")
@ResponseBody
public AjaxResult updateDynamicScheduledTask() {
dynamicScheduledTask.setCron("0/10 * * * * ?");
return new AjaxResult().success();
}
user.jsp
updateDynamicScheduledTask : function() {//动态修改定时任务
$.get("/user/updateDynamicScheduledTask", function(data) {
if (data.meta.success) {//动态修改定时任务成功
$.messager.alert('成功提示', "请重新刷新数据,有插入新的数据", 'info');
} else {
$.messager.alert('错误提示', data.meta.message, 'error');
}
}, 'json');
}
<a href="javascript:void(0)" class="easyui-linkbutton c8" iconCls="icon-search" data-url="updateDynamicScheduledTask">动态修改定时任务</a>
其他关联项目
- Spring Boot 系列教程13-注解定时任务
http://blog.csdn.net/je_ge/article/details/53434227 - Spring Boot 系列教程7-EasyUI-datagrid
http://blog.csdn.net/je_ge/article/details/53365189
源码地址
https://github.com/je-ge/spring-boot
如果觉得我的文章对您有帮助,请打赏支持。您的支持将鼓励我继续创作!谢谢!