GitHub
src="//ghbtns.com/github-btn.html?user=je-ge&repo=spring-boot&type=watch&count=true" scrolling="0" width="110" height="20">
动态修改定时任务cron参数
不需要重启应用就可以动态的改变Cron表达式的值不能使用@Scheduled(cron = “${jobs.cron}”)实现
动态定时任务类DynamicScheduledTask
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添加@EnableScheduling标注
@EnableScheduling
控制器UserController
@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/53434227Spring Boot 菜鸟教程 7 EasyUI-datagrid http://blog.csdn.net/je_ge/article/details/53365189
源码地址
https://github.com/je-ge/spring-boot
如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。 您的支持将鼓励我继续创作!谢谢!
转载请注明原文地址: https://ju.6miu.com/read-963573.html