spring schedule实现动态配置执行时间
作者:g-Jack 发布时间:2022-09-06 18:47:30
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的执行时间,生效时间为,上一个任务的执行周期,也可以满足我们现在需求,这样就可以实习项目更加的灵活!
@schedule注解动态配置时间间隔
动态配置时间间隔是通过自己实现的任务注册到任务调度实现的,并在每次调度的时候更改下次调度时间间隔,如果任务阻塞或者挂掉了就不会再被调度了,如果设置时间过长,到下次调度就需要等待很长时间。
import org.springframework.beans.factory.annotation.Autowired;
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.PeriodicTrigger;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
@EnableScheduling
public class DynamicScheduleTaskSecond implements SchedulingConfigurer {
private static final long WEEK_MILLIS = 604800000;
private static final long MIN_MILLIS = 1000;
private static long period = 1000;
static long l = System.currentTimeMillis();
@Autowired
SetPeriod setPeriod;
public static long getPeriod() {
return period;
}
public static void setPeriod(long period) {
DynamicScheduleTaskSecond.period = period;
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
try {
setPeriod.update(period);
System.out.println("abc");
Long last = System.currentTimeMillis() - l;
l = System.currentTimeMillis();
System.out.println(last);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
if (period < MIN_MILLIS || period > WEEK_MILLIS)
period = MIN_MILLIS;
PeriodicTrigger periodicTrigger = new PeriodicTrigger(period);
Date nextExecDate = periodicTrigger.nextExecutionTime(triggerContext);
return nextExecDate;
}
});
}
}
import org.springframework.stereotype.Component;
@Component
public class SetPeriod {
private static Long maxPeriod = 1000l;
public void update(Long period) {
maxPeriod += 1000;
setScheduleConfig(maxPeriod);
}
public boolean setScheduleConfig(Long period) {
DynamicScheduleTaskSecond.setPeriod(period);
return true;
}
}
上面是实现动态调度的一个简单实例,下面说一下基本原理。
动态调度功能主要是实现SchedulingConfigurer函数式接口,接口中的方法configureTasks的参数是重点。
@FunctionalInterface
public interface SchedulingConfigurer {
/**
* Callback allowing a {@link org.springframework.scheduling.TaskScheduler
* TaskScheduler} and specific {@link org.springframework.scheduling.config.Task Task}
* instances to be registered against the given the {@link ScheduledTaskRegistrar}.
* @param taskRegistrar the registrar to be configured.
*/
void configureTasks(ScheduledTaskRegistrar taskRegistrar);
}
看名字 ScheduledTaskRegistrar就知道是一个调度任务注册类,调用这个类的addTriggerTask方法需要两个参数
public void addTriggerTask(Runnable task, Trigger trigger) {
this.addTriggerTask(new TriggerTask(task, trigger));
}
一个是任务线程这个最后说,先说一下第二个Trigger,这是一个设置任务触发时间的接口,具体的实现有两个类,一个是CronTrigger对应的就是cron类型的时间设置,一个是PeriodicTrigger对应的就是FixDelay和FixRate两种方式的时间设置,实例中使用的是后者。
public interface Trigger {
@Nullable
Date nextExecutionTime(TriggerContext var1);
}
接口方法参数是一个TriggerContext,这个参数就是任务触发的上下文,里面保存着上一次任务开始时间和结束时间和实际执行用时,自己需要实现这个nextExecutionTime方法根据上一次任务执行时间来返回一个新的Date时间,new一个新的periodicTrigger对象初始化period时间间隔为新的时间间隔用nextExecutionTime方法就可以了根据上下文时间返回一个新的任务调度时间了,但是period的时间不能太长也不能太短最好设置一个区间,这样可以避免很多粗心的错误导致的麻烦,到此完美解决动态设置任务调度时间间隔功能。
再说一下第一个线程任务中的需要做的事,执行的任务需要在其他的具体类中实现,然后在这个线程中调用,然后每次在调度任务的时候就要根据时间业务重新设置时间间隔,比如读配置后改变时间间隔,也就是调度和具体的任务形成一个环,调度执行具体的任务后,具体的任务在设置调度的时间间隔。
来源:https://blog.csdn.net/hao134838/article/details/86604722


猜你喜欢
- 前言今天分享一个类似“孔雀开屏”的动画效果,打开新的页面时,新的页面从屏幕右上角以圆形逐渐打开到全屏。先来看下具体的效果不知道这种效果大家叫
- 1、用字符串分隔: using System.Text.RegularExpressions; string str="aaajs
- 本文实例为大家分享了C语言实现学生成绩管理系统的具体代码,供大家参考,具体内容如下结构体版的学生成绩管理系统主要功能有按1 输入学生信息按2
- Spring中常见问题1.NoSuchBeanDefinitionException2.'..Service' that c
- 一、前言在学习分治算法之前,问你一个问题,相信大家小时候都有存钱罐的经历,父母亲人如果给钱都会往自己的宝藏中存钱,我们每隔一段时间都会清点清
- 本文为大家分享了Tablayout简单的使用方法,供大家参考,具体内容如下一、TabLayout普通用法在项目中使用viewpager的时候
- 前言在SpringIOC中,我们熟知的BeanScope有单例(singleton)、原型(prototype), Bean的Scope影响
- 代码编译运行环境:VS2017+Debug+Win32按照参数形式的不同,C++应该有三种函数调用方式:传值调用、引用调用和指针调用。对于基
- 使用Java的NIO写的一个小的聊天系统,供大家参考,具体内容如下一、服务端/** * 群聊的服端 * * @author :breakpo
- 准备工作HALCON示例程序的描述部分一直是英文的,看起来很不方便。我决定汉化一下HALCON示例程序的描述,准备工作如下:拿到HALCON
- 前言如果你了解过 Liunx ,了解过 Liunx 的中管道命令 | ,那么你会发现,其实 Java 8 的 stream 和 Liunx
- 本文实例为大家分享了java排序算法之冒泡排序的具体代码,供大家参考,具体内容如下冒泡排序冒泡排序无疑是最为出名的排序算法之一,从序列的一端
- 二进制数据一般输入的格式是0x45, 0x3a, 0xc3, 这种数据格式看起来是16进制的字符串,但是实际上在存储的时候每个都对应一个字节
- 基本语法C#,又名Csharp,天朝喜欢叫C井。C#是一种面向对象的编程语言。在面向对象的程序设计方法中,程序有各种相互交互的对象组成。相同
- 提示出现unresolved external symbol _main搜了下找了下原因如下在创建MFC项目时
- 在日常Android手机的使用过程中,根据电话号码获得联系人头像,是经常会碰到的问题。本文即以实例形式讲述了Android根据电话号码获得联
- 第一步:图形验证码接口1.使用第三方的验证码生成工具Kaptchahttps://github.com/penggle/kaptcha@Co
- 功能需求:为软件设定一个使用有效期,当超过指定时间后,程序无法运行。实现思路:定义一个常量,用于记录一个时间,我们称之为标记时间,使用当前时
- 记录一下工作流的在Springboot中的使用,,顺便写个demo,概念,什么东西的我就不解释了,如有问题欢迎各位大佬指导一下。1.创建sp
- 一、Flutter代码的启动起点我们在多数的业务场景下,使用的都是FlutterActivity、FlutterFragment。在在背后,