广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot 实现动态添加定时任务功能
  • 690
分享到

SpringBoot 实现动态添加定时任务功能

2024-04-02 19:04:59 690人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录代码结构1. 配置类2. 定时任务类型枚举3. 实际执行任务实现类4. 定时任务包装器5. 任务注册器 (核心)6. 使用最后最近的需求有一个自动发布的功能, 需要做到每次提交都

最近的需求有一个自动发布的功能, 需要做到每次提交都要动态的添加一个定时任务

代码结构

1. 配置类

package com.orion.ops.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@EnableScheduling
@Configuration
public class SchedulerConfig {
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(4);
        scheduler.setRemoveOnCancelPolicy(true);
        scheduler.setThreadNamePrefix("scheduling-task-");
        return scheduler;
    }
}

2. 定时任务类型枚举

package com.orion.ops.handler.scheduler;
 
import com.orion.ops.consts.Const;
import com.orion.ops.handler.scheduler.impl.ReleaseTaskImpl;
import com.orion.ops.handler.scheduler.impl.SchedulerTaskImpl;
import lombok.AllArgsConstructor;
import java.util.function.Function;

@AllArgsConstructor
public enum TaskType {
    
    RELEASE(id -> new ReleaseTaskImpl((Long) id)) {
        @Override
        public String geTKEy(Object params) {
            return Const.RELEASE + "-" + params;
        }
    },
     * 调度任务
    SCHEDULER_TASK(id -> new SchedulerTaskImpl((Long) id)) {
            return Const.TASK + "-" + params;
    ;
    private final Function<Object, Runnable> factory;
     * 创建任务
     *
     * @param params params
     * @return task
    public Runnable create(Object params) {
        return factory.apply(params);
    }
     * 获取 key
     * @return key
    public abstract String getKey(Object params);
}

这个枚举的作用是生成定时任务的 runnable 和 定时任务的唯一值, 方便后续维护

3. 实际执行任务实现类

package com.orion.ops.handler.scheduler.impl;
 
import com.orion.ops.service.api.ApplicationReleaseService;
import com.orion.spring.SpringHolder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ReleaseTaskImpl implements Runnable {
    protected static ApplicationReleaseService applicationReleaseService = SpringHolder.getBean(ApplicationReleaseService.class);
    private Long releaseId;
    public ReleaseTaskImpl(Long releaseId) {
        this.releaseId = releaseId;
    }
    @Override
    public void run() {
        log.info("定时执行发布任务-触发 releaseId: {}", releaseId);
        applicationReleaseService.runnableAppRelease(releaseId, true);
}

4. 定时任务包装器

package com.orion.ops.handler.scheduler;
 
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;

public class TimedTask {
    
    private Runnable runnable;
     * 异步执行
    private volatile ScheduledFuture<?> future;
    public TimedTask(Runnable runnable) {
        this.runnable = runnable;
    }
     * 提交任务 一次性
     *
     * @param scheduler scheduler
     * @param time      time
    public void submit(TaskScheduler scheduler, Date time) {
        this.future = scheduler.schedule(runnable, time);
     * 提交任务 cron表达式
     * @param trigger   trigger
    public void submit(TaskScheduler scheduler, Trigger trigger) {
        this.future = scheduler.schedule(runnable, trigger);
     * 取消定时任务
    public void cancel() {
        if (future != null) {
            future.cancel(true);
        }
}

这个类的作用是包装实际执行任务, 以及提供调度器的执行方法

5. 任务注册器 (核心)

package com.orion.ops.handler.scheduler;
 
import com.orion.ops.consts.MessageConst;
import com.orion.utils.Exceptions;
import com.orion.utils.collect.Maps;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Component
public class TaskReGISter implements DisposableBean {
    private final Map<String, TimedTask> taskMap = Maps.newCurrentHashMap();
    @Resource
    @Qualifier("taskScheduler")
    private TaskScheduler scheduler;
    
    public void submit(TaskType type, Date time, Object params) {
        // 获取任务
        TimedTask timedTask = this.getTask(type, params);
        // 执行任务
        timedTask.submit(scheduler, time);
    }
     * @param cron   cron
    public void submit(TaskType type, String cron, Object params) {
        timedTask.submit(scheduler, new CronTrigger(cron));
     * 获取任务
    private TimedTask getTask(TaskType type, Object params) {
        // 生成任务
        Runnable runnable = type.create(params);
        String key = type.getKey(params);
        // 判断是否存在任务
        if (taskMap.containsKey(key)) {
            throw Exceptions.init(MessageConst.TASK_PRESENT);
        }
        TimedTask timedTask = new TimedTask(runnable);
        taskMap.put(key, timedTask);
        return timedTask;
     * 取消任务
    public void cancel(TaskType type, Object params) {
        TimedTask task = taskMap.get(key);
        if (task != null) {
            taskMap.remove(key);
            task.cancel();
     * 是否存在
    public boolean has(TaskType type, Object params) {
        return taskMap.containsKey(type.getKey(params));
    @Override
    public void destroy() {
        taskMap.values().forEach(TimedTask::cancel);
        taskMap.clear();
}

这个类提供了执行, 提交任务的api, 实现 DisposableBean 接口, 便于在bean销毁时将任务一起销毁

6. 使用

    @Resource
    private TaskRegister taskRegister;
    
    
    @RequestMapping("/submit")
    @EventLog(EventType.SUBMIT_RELEASE)
    public Long submitAppRelease(@RequestBody ApplicationReleaseRequest request) {
        Valid.notBlank(request.getTitle());
        Valid.notNull(request.getAppId());
        Valid.notNull(request.getProfileId());
        Valid.notNull(request.getBuildId());
        Valid.notEmpty(request.getMachineIdList());
        TimedReleaseType timedReleaseType = Valid.notNull(TimedReleaseType.of(request.getTimedRelease()));
        if (TimedReleaseType.TIMED.equals(timedReleaseType)) {
            Date timedReleaseTime = Valid.notNull(request.getTimedReleaseTime());
            Valid.isTrue(timedReleaseTime.compareTo(new Date()) > 0, MessageConst.TIMED_GREATER_THAN_NOW);
        }
        // 提交
        Long id = applicationReleaseService.submitAppRelease(request);
        // 提交任务
            taskRegister.submit(TaskType.RELEASE, request.getTimedReleaseTime(), id);
        return id;
    }

最后

       这是一个简单的动态添加定时任务的工具, 有很多的改造空间, 比如想持久化可以插入到库中, 定义一个 CommandLineRunner 在启动时将定时任务全部加载, 还可以给任务加钩子自动提交,自动删除等, 代码直接cv一定会报错, 就是一些工具, 常量类会报错, 改改就好了, 本人已亲测可用, 有什么问题可以在评论区沟通

到此这篇关于SpringBoot 实现动态添加定时任务功能的文章就介绍到这了,更多相关SpringBoot 定时任务内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot 实现动态添加定时任务功能

本文链接: https://www.lsjlt.com/news/140755.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • SpringBoot 实现动态添加定时任务功能
    目录代码结构1. 配置类2. 定时任务类型枚举3. 实际执行任务实现类4. 定时任务包装器5. 任务注册器 (核心)6. 使用最后最近的需求有一个自动发布的功能, 需要做到每次提交都...
    99+
    2022-11-13
  • 怎么用SpringBoot实现动态添加定时任务功能
    这篇“怎么用SpringBoot实现动态添加定时任务功能”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“怎么用SpringBo...
    99+
    2023-06-29
  • Spring动态添加定时任务的实现方法
    本篇内容主要讲解“Spring动态添加定时任务的实现方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Spring动态添加定时任务的实现方法”吧!一、背景在工作中,有些时候我们有些定时任务的执行...
    99+
    2023-06-20
  • Spring动态添加定时任务的实现思路
    一、背景 在工作中,有些时候我们有些定时任务的执行可能是需要动态修改的,比如: 生成报表,有些项目配置每天的8点生成,有些项目配置每天的10点生成,像这种动态的任务执行时间,在不考虑...
    99+
    2022-11-12
  • SpringBoot+Quartz实现动态定时任务
    本文实例为大家分享了springBoot+Quartz实现动态定时任务的具体代码,供大家参考,具体内容如下 目前常用的几种任务调度 Timer,简单无门槛,一般也没人用。spring...
    99+
    2022-11-13
  • django怎么动态添加定时任务
    在Django中,可以使用celery来实现动态添加定时任务。首先,需要安装Celery:```shellpip install c...
    99+
    2023-09-26
    django
  • SpringBoot动态定时任务如何实现
    这篇文章主要介绍了SpringBoot动态定时任务如何实现的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringBoot动态定时任务如何实现文章都会有所收获,下面我们一起来看看吧。 执行定时任务的...
    99+
    2023-07-05
  • SpringBoot定时任务功能怎么实现
    本篇内容介绍了“SpringBoot定时任务功能怎么实现”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!一 背景项目中需要一个可以动态新增定时...
    99+
    2023-06-30
  • SpringBoot动态定时任务实现完整版
    目录 执行定时任务的线程池配置类ScheduledFuture的包装类Runnable接口实现类定时任务注册类定时任务示例类数据库表设计实体类定时任务预热工具类定时任务的:...
    99+
    2023-02-23
    springboot动态定时任务 springboot 定时任务
  • 怎么用Python Celery动态添加定时任务
    一、背景实际工作中会有一些耗时的异步任务需要使用定时调度,比如发送邮件,拉取数据,执行定时脚本通过celery 实现调度主要思想是 通过引入中间人redis,启动 worker 进行任务执行 ,celery-beat进行定时任务数据存储二、...
    99+
    2023-05-14
    Python Celery
  • Springboot实现动态定时任务流程详解
    目录一、静态二、动态1、基本代码2、方案详解2.1 初始化2.2 单次执行2.3 停止任务2.4 启用任务三、小结一、静态 静态的定时任务可以直接使用注解@Scheduled,并在启...
    99+
    2022-11-13
  • SpringBoot实现固定、动态定时任务 | 三种实现方式
    前言: 阅读完本文:🐱‍👓 知晓 SpringBoot 用注解如何实现定时任务明白 SpringBoot 如何实现一个动态定时任务 (与数据库相关联实现)理解 SpringBoot 实现设置时间执行定时任务 ...
    99+
    2023-10-01
    spring boot java mybatis
  • Python Celery动态添加定时任务生产实践指南
    目录一、背景二、Celery动态添加定时任务的官方文档三、celery简单实用3.1 基础环境配置3.2 测试使用Celery应用四、配置backend存储任务执行结果 四...
    99+
    2022-11-11
  • 如何使用Python Celery动态添加定时任务
    本篇内容介绍了“如何使用Python Celery动态添加定时任务”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!一、背景实际工作中...
    99+
    2023-07-06
  • 详解SpringBoot定时任务功能
    目录一 背景二 动态定时任务调度三 多节点任务执行问题四 后记一 背景 项目中需要一个可以动态新增定时定时任务的功能,现在项目中使用的是xxl-job定时任务调度系统,但是经过一番对...
    99+
    2022-11-13
  • SpringBoot实现动态定时任务的示例代码
    目录前言配置文件定时任务核心类提供修改cron表达式的controller前言 之前在SpringBoot项目中简单使用定时任务,不过由于要借助cron表达式且都提前定义好放在配置文...
    99+
    2022-11-13
    SpringBoot动态定时任务 SpringBoot 定时任务
  • 如何实现SpringBoot+Quartz+Maven+MySql动态定时任务
    下面一起来了解下如何实现SpringBoot+Quartz+Maven+MySql动态定时任务,相信大家看完肯定会受益匪浅,文字在精不在多,希望如何实现SpringBoot+Quartz+Maven+MyS...
    99+
    2022-10-18
  • SpringBoot实现动态多线程并发定时任务
    本文实例为大家分享了SpringBoot实现动态多线程并发定时任务的具体代码,供大家参考,具体内容如下 实现定时任务有多种方式,使用spring自带的,继承SchedulingCon...
    99+
    2022-11-12
  • SpringBoot动态定时任务(完整版)
    本文定时任务功能(增、删、改、启动、暂停) 话不多说,直接上代码,你们直接CV就可以用!!!  执行定时任务的线程池配置类 import org.springframework.context.annotation.Bean;im...
    99+
    2023-08-30
    spring boot java spring
  • SpringBoot如何设置动态定时任务
    这篇文章主要介绍了SpringBoot如何设置动态定时任务的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringBoot如何设置动态定时任务文章都会有所收获,下面我们一起来看看吧。之前写过文章记录怎么在Sp...
    99+
    2023-07-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作