In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this article "how to use SpringBoot to dynamically add timed tasks", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use SpringBoot to dynamically add timed tasks" article.
The recent requirement has an automatic release function, which needs to dynamically add a scheduled task for each submission.
Code structure
1. Configuration class 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 / * Scheduler configuration * * @ author Jiahang Li * @ version 1.0.0 * @ since 9:51 * / @ EnableScheduling@Configurationpublic class SchedulerConfig {@ Bean public TaskScheduler taskScheduler () {ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler (); scheduler.setPoolSize (4); scheduler.setRemoveOnCancelPolicy (true); scheduler.setThreadNamePrefix ("scheduling-task-"); return scheduler;}} 2. Scheduled task type enumeration 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 / * author Jiahang Li * @ version 1.0.0 * @ since 10:16 on 2022-2-14 * / @ AllArgsConstructorpublic enum TaskType {/ * publish task * / RELEASE (id-> new ReleaseTaskImpl ((Long) id)) {@ Override public String getKey (Object params) {return Const.RELEASE + "-" + params }}, * schedule task SCHEDULER_TASK (id-> new SchedulerTaskImpl ((Long) id)) {return Const.TASK + "-" + params;; private final Function factory; * create task * * @ param params params * @ return task public Runnable create (Object params) {return factory.apply (params) } * get key * @ return key public abstract String getKey (Object params);}
The purpose of this enumeration is to generate the runnable of the scheduled task and the unique value of the scheduled task for subsequent maintenance.
3. Actual task implementation class package com.orion.ops.handler.scheduler.impl; import com.orion.ops.service.api.ApplicationReleaseService;import com.orion.spring.SpringHolder;import lombok.extern.slf4j.Slf4j;/** * release task implementation * * @ author Jiahang Li * @ version 1.0.0 * @ since 10:25 * / @ Slf4jpublic 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 ("scheduled release tasks-trigger releaseId: {}", releaseId); applicationReleaseService.runnableAppRelease (releaseId, true);} 4. Scheduled task wrapper 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;/** * scheduled task wrapper * * @ author Jiahang Li * @ version 1.0.0 * @ since 10:34 on 2022-2-14 * / public class TimedTask {/ * Task * / private Runnable runnable * asynchronously execute private volatile ScheduledFuture future; public TimedTask (Runnable runnable) {this.runnable = runnable;} * submit tasks once * * @ param scheduler scheduler * @ param time time public void submit (TaskScheduler scheduler, Date time) {this.future = scheduler.schedule (runnable, time) * submit task cron expression * @ param trigger trigger public void submit (TaskScheduler scheduler, Trigger trigger) {this.future = scheduler.schedule (runnable, trigger); * cancel scheduled task public void cancel () {if (future! = null) {future.cancel (true);}}
The purpose of this class is to wrap the actual execution of the task and to provide the execution method of the scheduler
5. Task Registry (Core) 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 / * * @ author Jiahang Li * @ version 1.0.0 * @ since 10:46 on 2022-2-14 * / @ Componentpublic class TaskRegister implements DisposableBean {private final Map taskMap = Maps.newCurrentHashMap (); @ Resource @ Qualifier ("taskScheduler") private TaskScheduler scheduler / * submit task * * @ param type type * @ param time time * @ param params params * / public void submit (TaskType type, Date time, Object params) {/ / get the task TimedTask timedTask = this.getTask (type, params); / / execute the task timedTask.submit (scheduler, time) } * @ param cron cron public void submit (TaskType type, String cron, Object params) {timedTask.submit (scheduler, new CronTrigger (cron)); * get task private TimedTask getTask (TaskType type, Object params) {/ / generate task Runnable runnable = type.create (params); String key = type.getKey (params) / / determine whether there is a task if (taskMap.containsKey (key)) {throw Exceptions.init (MessageConst.TASK_PRESENT);} TimedTask timedTask = new TimedTask (runnable); taskMap.put (key, timedTask); return timedTask; * cancel task public void cancel (TaskType type, Object params) {TimedTask task = taskMap.get (key) If (task! = null) {taskMap.remove (key); task.cancel (); * whether there is public boolean has (TaskType type, Object params) {return taskMap.containsKey (type.getKey (params)); @ Override public void destroy () {taskMap.values () .forEach (TimedTask::cancel); taskMap.clear ();}
This class provides the api to execute and submit the task, and implements the DisposableBean interface, so that the task can be destroyed together when the bean is destroyed.
6. Use @ Resource private TaskRegister taskRegister; / * to submit the publication * / @ 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) } / / submit Long id = applicationReleaseService.submitAppRelease (request); / / submit task taskRegister.submit (TaskType.RELEASE, request.getTimedReleaseTime (), id); return id } the above is about the content of this article on "how to dynamically add scheduled tasks with SpringBoot". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.