Spring 定時任務動態管理

管理 Spring 中定時任務

pom.xml

<properties><hutool.version>5.6.6</hutool.version><lombok.version>1.18.20</lombok.version><spring-boot.web.version>2.2.10.RELEASE</spring-boot.web.version>
</properties><dependencys><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>${hutool.version}</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>${spring-boot.web.version}</version></dependency>
</dependencys>

application.yml

server:port: 8081spring:application:name: SIYUAN-SPRINGBOOT-SERVER

SYSpringBootApplication

package run.siyuan.springboot;import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;import java.lang.reflect.Field;
import java.util.Set;/*** @className: SYSpringBootApplication* @Description: TODO* @author: siyuan* @date: 2022/4/27 2:58 PM*/
@Slf4j
@RestController
@EnableScheduling
@SpringBootApplication
public class SYSpringBootApplication {@Autowiredprivate ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor;public static void main(String[] args) {SpringApplication.run(SYSpringBootApplication.class, args);}@Scheduled(cron = "0/5 * * * * ?")public void schedulingMessage1() {log.info("時間:{} 打印的日志,Method Name:{}", DateUtil.formatDateTime(DateUtil.date()), "schedulingMessage1");}@Scheduled(cron = "0/5 * * * * ?")public void schedulingMessage2() {log.info("時間:{} 打印的日志,Method Name:{}", DateUtil.formatDateTime(DateUtil.date()), "schedulingMessage2");}@GetMapping("/cancelTask")public Object cancelTask(String methodFullName) {Set<ScheduledTask> tasks = scheduledAnnotationBeanPostProcessor.getScheduledTasks();for (ScheduledTask task : tasks) {if (task.getTask().getRunnable().toString().equals(methodFullName)) {task.cancel();}}return "success";}@GetMapping("/updateTask")public String updateTask(@RequestBody JSONObject json) throws NoSuchFieldException, IllegalAccessException {String cron = json.getStr("cron");String methodFullName = json.getStr("methodFullName");Field registrar = scheduledAnnotationBeanPostProcessor.getClass().getDeclaredField("registrar");registrar.setAccessible(true);ScheduledTaskRegistrar taskRegistrar = (ScheduledTaskRegistrar)registrar.get(scheduledAnnotationBeanPostProcessor);TaskScheduler scheduler = taskRegistrar.getScheduler();Set<ScheduledTask> scheduledTaskSet = scheduledAnnotationBeanPostProcessor.getScheduledTasks();for (ScheduledTask task : scheduledTaskSet){if (task.getTask().getRunnable().toString().equals(methodFullName)){task.cancel();CronTask cronTask = new CronTask(task.getTask().getRunnable(), cron);scheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());}}return "success";}}

驗證

### 取消指定定時任務
GET http://localhost:8081/cancelTask?methodFullName=run.siyuan.springboot.SYSpringBootApplication.schedulingMessage1
### 更新任務周期
GET http://localhost:8081/updateTask
Content-Type: application/json{"cron": "0/10 * * * * ?","methodFullName": "run.siyuan.springboot.SYSpringBootApplication.schedulingMessage2"
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273539.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273539.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273539.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

高效率Oracle SQL語句

1、Where子句中的連接順序&#xff1a; ORACLE采用自下而上的順序解析WHERE子句。 根據這個原理&#xff0c;表之間的連接必須寫在其他WHERE條件之前&#xff0c; 那些可以過濾掉最大數量記錄的條件必須寫在WHERE子句的末尾。 舉例&#xff1a; (低效) select ... from table1…

RabbitMQ Management:Management API returned status code 500

錯誤顯示&#xff1a; 解決方案&#xff1a; 因為是使用docker 容器安裝的&#xff0c;所有需要進入容器 docker exec -it rabbitmq /bin/bash進入目錄 cd /etc/rabbitmq/conf.d/執行命令 echo management_agent.disable_metrics_collector false > management_agent.dis…

Android JNI和NDK學習(5)--JNI分析API

Java類型和本地類型對應 在如下情況下&#xff0c;需要在本地方法中應用java對象的引用&#xff0c;就會用到類型之間的轉換&#xff1a; java方法里面將參數傳入本地方法&#xff1b;在本地方法里面創建java對象&#xff1b;在本地方法里面return結果給java程序。Java基本類型…

RabbitMq 消費失敗,重試機制

方案一&#xff1a; 本地消息表 定時任務 本地消息表&#xff1a;主要用于存儲 業務數據、交換機、隊列、路由、次數 定時任務&#xff1a;定時掃描本地消息表&#xff0c;重新給業務隊列投遞消息。 具體思路&#xff1a;業務隊列消費失敗時&#xff0c;把 業務數據、交換機、…

Android常用的工具類

主要介紹總結的Android開發中常用的工具類&#xff0c;大部分同樣適用于Java。目前包括HttpUtils、DownloadManagerPro、ShellUtils、PackageUtils、 PreferencesUtils、JSONUtils、FileUtils、ResourceUtils、StringUtils、 ParcelUtils、RandomUtils、ArrayUtils、ImageUtils…

0. Spring 基礎

BeanDefinition BeanDefinition 表示 Bean 定義&#xff1a; Spring根據BeanDefinition來創建Bean對象&#xff1b;BeanDefinition有很多的屬性用來描述Bean&#xff1b;BeanDefiniton是Spring中非常核心的概念。BeanDefiniton中重要的屬性&#xff1a; a. beanClass&#xf…

1. Spring 源碼:Spring 解析XML 配置文件,獲得 Bena 的定義信息

通過 Debug 運行 XmlBeanDefinitionReaderTests 類的 withFreshInputStream() 的方法&#xff0c;調試 Spring 解析 XML 配置文件&#xff0c;獲得 Bean 的定義。 大體流程可根據序號查看&#xff0c;xml 配置文件隨便看一眼&#xff0c;不用過多在意。 <?xml version&qu…

c++ 讀取文件 最后一行讀取了兩次

用ifstream的eof()&#xff0c;竟然讀到文件最后了&#xff0c;判斷eof還為false。網上查找資料后&#xff0c;終于解決這個問題。 參照文件&#xff1a;http://tuhao.blogbus.com/logs/21306687.html 在使用C/C讀文件的時候&#xff0c;一定都使用過eof&#xff08;&#xff0…

java中的io系統詳解(轉)

Java 流在處理上分為字符流和字節流。字符流處理的單元為 2 個字節的 Unicode 字符&#xff0c;分別操作字符、字符數組或字符串&#xff0c;而字節流處理單元為 1 個字節&#xff0c;操作字節和字節數組。 Java 內用 Unicode 編碼存儲字符&#xff0c;字符流處理類負責將外部的…

js獲取字符串最后一個字符代碼

方法一&#xff1a;運用String對象下的charAt方法 charAt() 方法可返回指定位置的字符。 代碼如下 復制代碼 str.charAt(str.length – 1) 請注意&#xff0c;JavaScript 并沒有一種有別于字符串類型的字符數據類型&#xff0c;所以返回的字符是長度為 1 的字符串 方法二&#…

Unity3D Shader入門指南(二)

關于本系列 這是Unity3D Shader入門指南系列的第二篇&#xff0c;本系列面向的對象是新接觸Shader開發的Unity3D使用者&#xff0c;因為我本身自己也是Shader初學者&#xff0c;因此可能會存在錯誤或者疏漏&#xff0c;如果您在Shader開發上有所心得&#xff0c;很歡迎并懇請您…

JVM:如何分析線程堆棧

英文原文&#xff1a;JVM: How to analyze Thread Dump 在這篇文章里我將教會你如何分析JVM的線程堆棧以及如何從堆棧信息中找出問題的根因。在我看來線程堆棧分析技術是Java EE產品支持工程師所必須掌握的一門技術。在線程堆棧中存儲的信息&#xff0c;通常遠超出你的想象&…

一個工科研究生畢業后的職業規劃

http://blog.csdn.net/wojiushiwo987/article/details/8592359一個工科研究生畢業后的職業規劃 [wojiushiwo987個人感觸]:說的很誠懇&#xff0c;對于馬上面臨畢業的我很受用&#xff0c;很有啟發。有了好的職業生涯規劃&#xff0c;才有了前進的方向和動力&#xff0c;才能…

SQLSERVER中如何忽略索引提示

SQLSERVER中如何忽略索引提示 原文:SQLSERVER中如何忽略索引提示SQLSERVER中如何忽略索引提示 當我們想讓某條查詢語句利用某個索引的時候&#xff0c;我們一般會在查詢語句里加索引提示&#xff0c;就像這樣 SELECT id,name from TB with (index(IX_xttrace_bal)) where bal…

JavaScript——以簡單的方式理解閉包

閉包&#xff0c;在一開始接觸JavaScript的時候就聽說過。首先明確一點&#xff0c;它理解起來確實不復雜&#xff0c;而且它也非常好用。那我們去理解閉包之前&#xff0c;要有什么基礎呢&#xff1f;我個人認為最重要的便是作用域&#xff08;lexical scope&#xff09;&…

jquery實現二級聯動不與數據庫交互

<select id"pro" name"pro" style"width:90px;"></select> <select id"city" name"city" style"width: 90px"></select> $._cityInfo [{"n":"北京市","c"…

[016]轉--C++拷貝構造函數詳解

一. 什么是拷貝構造函數 首先對于普通類型的對象來說&#xff0c;它們之間的復制是很簡單的&#xff0c;例如&#xff1a; [c-sharp] view plaincopy int a 100; int b a; 而類對象與普通對象不同&#xff0c;類對象內部結構一般較為復雜&#xff0c;存在各種成員變量。下…

js中調用C標簽實現百度地圖

<script type"text/javascript"> //json數組 var jsonArray document.getElementById("restaurant").value; var map new BMap.Map("milkMap"); // 創建地圖實例 <c:forEach items"${restaurantlist}" var"…

jquery較驗組織機構編碼

//*************************組織機構碼較驗************************* function checkOrganizationCode() { var weight [3, 7, 9, 10, 5, 8, 4, 2]; var str 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ; var reg /^([0-9A-Z]){8}-[0-9|X]{1}$/; var organizationcode $("…

自定義GrildView實現單選功能

首先看實現功能截圖&#xff0c;這是一個自定義Dialog,并且里面內容由GrildView 綁定數據源&#xff0c;實現類似單選功能。 首先自定義Dialog&#xff0c;綁定數據源 自定義Dialog彈出框大小方法 最主要實現的就是點擊顏色切換的功能&#xff0c;默認GrildView的每一項都是藍色…