使用spring-task定时任务动态配置修改执行时间
作者:丶人生如梦 发布时间:2021-12-12 08:10:40
标签:spring-task,定时任务,配置,执行时间
spring-task定时任务动态配置修改执行时间
因项目需要,几个定时任务需要人为动态设置执行时间,于是乎吧,就查阅相关资料,是可以动态设置的,废话不多说,直接上代码,一目了然。
package com.seckill.quartz;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by loup on 2017/11/11.
*/
@Component
@EnableScheduling
public class DynamicScheduledTask implements SchedulingConfigurer {
//时间表达式 每2秒执行一次
private String cron = "0/2 * * * * ?";
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
//任务逻辑
System.out.println("---------------start-------------------");
System.out.println("动态修改定时任务参数,时间表达式cron为:" + cron);
System.out.println("当前时间为:" + sdf.format(new Date()));
System.out.println("----------------end--------------------");
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
CronTrigger cronTrigger = new CronTrigger(cron);
Date nextExecDate = cronTrigger.nextExecutionTime(triggerContext);
return nextExecDate;
}
});
}
public void setCron(String cron) {
this.cron = cron;
}
}
这个是定时任务调度执行器,采用的是注解的方式。首先要动态配置,要设置为@EnableScheduling,这是确保能够动态,然后实现SchedulingConfigurer,重写configureTasks方法,接下来就是这个的相关spring配置文件,要引入下面这个task,不然识别不了啊,配置文件就是这么简单
http://www.springframework.org/schema/task
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.seckill.quartz"/>
<task:annotation-driven />
</beans>
接下来就是写测试类,测试可不可行啊
package com.seckill.quartz;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
/**
* Created by loup on 2017/11/11.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:/conf/spring-quartz.xml"})
public class QuartzTest {
@Autowired
private DynamicScheduledTask dynamicScheduledTask;
@Test
public void test1(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
dynamicScheduledTask.setCron("0/10 * * * * ?");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行测试类,查看结果,达到效果,亲测可用
spring schedule 动态配置执行时间
之前saas平台实现动态修改定时任务的时间,都是通过xx-job这样的框架来实现,这样我们可以单独一个服务来管理我们整个saas平台的定时任务,但是最近给银行做的一个小项目,需要本地化部署,所以我不想弄很多的服务,并且他们并没有要求修改以后即时生效,所以我直接采用了 spring schedule结合mysql动态配置执行时间。
之前我们用的schedule通过注解的方式,只能用静态的corn表达式,如果想实现动态的需要实现SchedulingConfigurer,并且通过注解@EnableScheduling。如下:
package com.zqf.marketing.task;
import com.zqf.db.marketingrobot.sys.model.RobotSysSwitch;
import com.zqf.marketing.sys.service.SwitchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* @author zhenghao
* @description
* @date 2019/1/22 21:50
*/
@Lazy(false)
@Service
@EnableScheduling
public class TestTaskService implements SchedulingConfigurer {
private static Logger log = LoggerFactory.getLogger(TestTaskService.class);
@Autowired
private SwitchService switchService;
private String SpringDynamicCronTask() {
String cron = "0/5 * * * * ?";
//从数据库获得配置的corn表达式
RobotSysSwitch switchById = switchService.getSwitchById(5L);
cron = switchById.getSwitchFlag();
log.info(cron);
return cron;
}
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
// 任务逻辑
log.info("task_task_tak");
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
String s = SpringDynamicCronTask();
// 任务触发,可修改任务的执行周期
CronTrigger trigger = new CronTrigger(s);
Date nextExec = trigger.nextExecutionTime(triggerContext);
return nextExec;
}
});
}
}
这样我们就可以动态的修改task的执行时间,生效时间为,上一个任务的执行周期,也可以满足我们现在需求,这样就可以实习项目更加的灵活!
来源:https://blog.csdn.net/ll840768874/article/details/78507286
0
投稿
猜你喜欢
- ListBox控件的使用: 1)控件属性 Items SelectedItems SelectioModes 2)数据绑定 DataSour
- Android图片的处理工具类BitmapUtils,供大家参考,具体内容如下项目中经常会用到图片,所以在这先简单的总结一下。闲言少叙,上代
- 代码如下:@Test public void shengdanshu(){ //叶子层
- 今天写这篇文章的缘由是前一段时间一个网友在我的博客上面留言,想要实现在GridLayout(相当于九宫格)中点击每项可左右滑动显
- 目标多级表头、分页、动态数据实现依赖<!-- poi工具类--> &nbs
- 本文实例讲述了Android SQLite数据库操作方法。分享给大家供大家参考,具体如下:SQLite and AndroidSQLite简
- 事务介绍一个事务要么同时成功,要么同时失败特性Atomic原子性 事务是由一个或多个活动组成的一个工作单元。原子性确保事务中的所有操作全部发
- 在WPF的DrawingContext对象中,提供了基本的绘制椭圆和矩形的API:DrawEllipse和DrawRectangle。但是,
- java实现在线预览- -之poi实现word、excel、ppt转html,具体内容如下所示:###简介java实现在线预览功能是一个大家
- 在微服务中,需要我们在各个微服务中共享Session,使用Redis来共享Session是一个很好的解决方法,Redis是运行在内存中,查取
- 1.MyBatis动态SQLMyBatis 的强大特性之一便是它的动态 SQL,即拼接SQL字符串。如果你有使用 JDBC 或其他类似框架的
- JSR303简介JSR-303 是 JAVA EE 6 中的一项子规范,叫做 Bean Validation,官方参考实现是Hibernat
- using System;using System.Collections.Generic;using System.Web.Script.
- try { using (TransactionScope tr = new Transact
- StringUtils.isBlank()的使用在校验一个String类型的变量是否为空时,可以使用StringUtils.isBlank方
- C#中的null与SQL中的NULL是不一样的,SQL中的NULL用C#表示出来就是DBNull.Value。注意:SQL参数是不能接受C#
- 前言平时我们都有用到LeakCanary来分析内存泄露的情况,这里可以来看看LeakCanary是如何实现的,它的内部又有哪些比较有意思的操
- 背景笔者使用 Spring Security 5.8 时,发现网上很多教程所教的 Spring Security 配置类 SecurityC
- 问题描述最近IDEA抽风了,不管是新建SpringBoot工程,还是导入项目。IDEA代码里面都会飘红~Build项目时,会提示错误:错误:
- SpringMVC的几个模型对象模型对象的作用主要是保存数据,可以借助它们将数据带到前端。常用的模型对象有以下几个:1.ModelAndVi