Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of fixedDelayString loading properties configuration in @ Scheduled

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the example analysis of fixedDelayString loading properties configuration in @ Scheduled, which is very detailed and has certain reference value. Friends who are interested must read it!

@ Scheduled fixedDelayString loads properties configuration @ Componentpublic class ScheduledServiceImpl {@ Scheduled (fixedDelayString = "${eventTracking.delayFixed}") private void doTask () {Timestamp timestamp = new Timestamp (System.currentTimeMillis ()); System.out.println ("current time >" + timestamp.toString ());}} @ Scheduled executes the original understanding: preface

This paper introduces the execution principle of using scheduled tasks in Spring Boot.

Two: @ Scheduled usage

The scheduled task is annotated as @ Scheduled. Examples of usage are as follows:

/ / defines a scheduled task that is executed at 16:00 every day. @ Scheduled (cron = "00 16 * *?) public void depositJob () {/ / execute code} / / defines a scheduled task to be executed at a certain frequency. @ Scheduled (fixedRate = 1000 * 60) public void job2 () {/ / execute code} / / defines a scheduled task to be executed at a certain frequency, and is executed every 1 minute. Delay 1 second to execute @ Scheduled (fixedRate = 1000 * 60 initialDelay = 1000) public void updatePayRecords () {/ / execute code}

Note: for specific parameters, please refer to the "org.springframework.scheduling.annotation.Scheduled" class under "spring-context-4.2.4.RELEASE.jar".

Three: @ Scheduled code execution principle description

Brief introduction: after initializing the bean, spring intercepts all the methods using the "@ Scheduled" annotation through "postProcessAfterInitialization", parses the corresponding annotation parameters, and puts them into the "scheduled task list" for subsequent processing; after that, the "scheduled task list" uniformly executes the corresponding scheduled tasks (tasks are executed sequentially, cron is executed first, and then fixedRate is executed).

The important code is as follows:

Step 1: load all the class methods that implement Scheduled annotations in turn.

/ / Note: ScheduledAnnotationBeanPostProcessor inherits BeanPostProcessor. @ Overridepublic Object postProcessAfterInitialization (final Object bean, String beanName) {/ / omit multiple judgment condition codes for (Map.Entry entry: annotatedMethods.entrySet ()) {Method method = entry.getKey (); for (Scheduled scheduled: entry.getValue ()) {processScheduled (scheduled, method, bean);}} return bean;}

Step 2: put the corresponding type of timer into the corresponding "scheduled task list".

/ / Note: ScheduledAnnotationBeanPostProcessor inherits BeanPostProcessor. / / get the parameters of the scheduled class, and then put them into different task lists according to the parameter type, corresponding delay time and corresponding time zone. Protected void processScheduled (Scheduled scheduled, Method method, Object bean) {/ / get the corn type String cron = scheduled.cron (); if (StringUtils.hasText (cron)) {Assert.isTrue (initialDelay = =-1, "'initialDelay' not supported for cron triggers"); processedSchedule = true String zone = scheduled.zone (); / / put in cron task list (not executed) this.registrar.addCronTask (new CronTask (runnable, new CronTrigger (cron, timeZone));} / / execution frequency type (long type) long fixedRate = scheduled.fixedRate (); String fixedDelayString = scheduled.fixedDelayString (); if (fixedRate > = 0) {Assert.isTrue (! processedSchedule, errorMessage) ProcessedSchedule = true; / / put in the FixedRate task list (not executed) (registrar is ScheduledTaskRegistrar) this.registrar.addFixedRateTask (new IntervalTask (runnable, fixedRate, initialDelay));} / / execution frequency type (string type, does not receive parameter calculations such as: 600: 20) String fixedRateString = scheduled.fixedRateString (); if (StringUtils.hasText (fixedRateString)) {Assert.isTrue (! processedSchedule, errorMessage) ProcessedSchedule = true; if (this.embeddedValueResolver! = null) {fixedRateString = this.embeddedValueResolver.resolveStringValue (fixedRateString);} fixedRate = Long.parseLong (fixedRateString); / / put in the FixedRate task list (not executed) this.registrar.addFixedRateTask (new IntervalTask (runnable, fixedRate, initialDelay));}} return bean;}

Step 3: perform the corresponding scheduled tasks.

Description: the scheduled task first executes the corn, judges the execution time of the scheduled task, calculates the corresponding next execution time, puts it into the thread, and executes it after the corresponding time. The scheduled tasks executed by "fixedRate" are then executed until all tasks are finished.

Protected void scheduleTasks () {/ / execute the corresponding Cron if (this.cronTasks! = null) {for (CronTask task: this.cronTasks) {this.scheduledFutures.add (this.taskScheduler.schedule (task.getRunnable (), task.getTrigger ()) sequentially) }} / / execute all "fixedRate" scheduled tasks sequentially (no delay, that is, the initialDelay parameter is empty). Because there is no delay, the scheduled task will be executed directly once. After the task is completed, the time of the next task will be put into the delayedExecute to wait for the next execution. If (this.fixedRateTasks! = null) {for (IntervalTask task: this.fixedRateTasks) {if (task.getInitialDelay () > 0) {Date startTime = new Date (now + task.getInitialDelay ()); this.scheduledFutures.add (this.taskScheduler.scheduleAtFixedRate (task.getRunnable (), startTime, task.getInterval () } else {this.scheduledFutures.add (this.taskScheduler.scheduleAtFixedRate (task.getRunnable (), task.getInterval () } / / execute all "fixedRate" scheduled tasks sequentially (with delay, that is, the initialDelay parameter is not empty) if (this.fixedDelayTasks! = null) {for (IntervalTask task: this.fixedDelayTasks) {if (task.getInitialDelay () > 0) {Date startTime = new Date (now + task.getInitialDelay ()) This.scheduledFutures.add (this.taskScheduler.scheduleWithFixedDelay (task.getRunnable (), startTime, task.getInterval ());} else {this.scheduledFutures.add (this.taskScheduler.scheduleWithFixedDelay (task.getRunnable (), task.getInterval ();}

Next, take a look at the scheduled task run (extends self-Runnable API) method:

/ / Note: after each execution of a scheduled task, the execution time of the next scheduled task will be set to confirm the execution time of the next task. Public void run () {boolean periodic = isPeriodic (); if (! canRunInCurrentRunState (periodic)) cancel (false); else if (! periodic) ScheduledFutureTask.super.run (); else if (ScheduledFutureTask.super.runAndReset ()) {setNextRunTime (); reExecutePeriodic (outerTask);}}

Note 1: as you can see from the above code, if multiple scheduled tasks are defined at the same time, they are also executed sequentially and will be executed according to the order in which the program loads the Scheduled method.

But what happens if the execution of a scheduled task is not completed?

A: this task cannot be completed all the time, and the next task execution time cannot be set. After that, all scheduled tasks behind this task cannot continue to be executed, and all scheduled tasks will become invalid.

Therefore, in the application of the method of timing tasks in springBoot, the phenomena of "endless loop" and "http waiting for no response" must not appear, otherwise it will lead to the failure of the scheduled task program. In addition, the scheduled tasks can be "dispersed" under non-special needs.

The above is all the content of the article "sample Analysis of fixedDelayString loading properties configuration in @ Scheduled". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report