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

What are the ways to implement scheduled tasks in Java

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "what are the ways to implement scheduled tasks in Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what are the ways to implement scheduled tasks in Java?"

1. The thread waits for the implementation

Let's explain it in the most primitive and simplest way. You can first create a thread, and then let it run all the time in the while loop, through the sleep method to achieve the effect of scheduled tasks.

Public class Task {public static void main (String [] args) {/ / run ina second final long timeInterval = 1000; Runnable runnable = new Runnable () {@ Override public void run () {while (true) {System.out.println ("Hello!!") Try {Thread.sleep (timeInterval);} catch (InterruptedException e) {e.printStackTrace ();}; Thread thread = new Thread (runnable); thread.start ();}}

This approach is simple and straightforward, but the functions that can be realized are limited and need to be implemented on their own.

2. JDK has its own Timer implementation.

At present, the Timer API that comes with JDK is the oldest way to implement scheduled tasks. Timer is a timer tool that is used to schedule a specified task in a background thread. It can schedule tasks to be "executed once" or "executed multiple times" on a regular basis.

In actual development, some periodic operations are often required, such as performing an operation every 5 minutes. The most convenient and efficient way to implement such operations is to use the java.util.Timer utility class.

2.1 Core approach

The core methods of the imer class are:

/ / execute the specified task schedule (TimerTask task,long delay) after the specified delay time; / / execute the specified task at the specified time. (execute only once) schedule (TimerTask task, Date time); / / after delaying the specified time (delay), start to repeat the specified task schedule (TimerTask task,long delay,long period) at the specified interval (period); / / repeat the specified task schedule (TimerTask task, Date firstTime, long period) at the specified interval (period) at the specified time / / start repetitive fixed-rate execution tasks scheduleAtFixedRate (TimerTask task,Date firstTime,long period) at the specified time; / / start repetitive fixed-rate execution tasks scheduleAtFixedRate (TimerTask task,long delay,long period) after the specified delay; / / terminate this timer and discard all currently scheduled tasks. Cancal (); / / removes all cancelled tasks from the task queue of this timer. Purge (); 2.2 use examples

Here are a few examples to demonstrate the use of the core method. First define a generic TimerTask class that defines the tasks to be performed with.

Public class DoSomethingTimerTask extends TimerTask {private String taskName; public DoSomethingTimerTask (String taskName) {this.taskName = taskName;} @ Override public void run () {System.out.println (new Date () + ": task"+ taskName +"executed.") ;} 2.2.1 specify a delay in execution

It is a common scenario to execute once after a specified delay time

For example, when the system initializes a component, it is delayed for a few seconds, and then the scheduled task is executed.

Public class DelayOneDemo {public static void main (String [] args) {Timer timer = new Timer (); timer.schedule (new DoSomethingTimerTask ("DelayOneDemo"), 1000L);}}

Execute the above code, execute the scheduled task after a delay of one second, and print the result. The second parameter is in milliseconds.

2.2.2 execution at fixed intervals

The scheduled task starts to be executed at a specified delay time, and the scheduled task is executed at fixed intervals. For example, the execution delay is 2 seconds, and the fixed execution interval is 1 second.

Public class PeriodDemo {public static void main (String [] args) {Timer timer = new Timer (); timer.schedule (new DoSomethingTimerTask ("PeriodDemo"), 2000L, 1000L);}}

If you execute the program, you will find that it starts to be executed every 1 second after 2 seconds.

2.2.3 fixed rate execution

The scheduled task starts to be executed at a specified delay time, and the scheduled task is executed at a fixed rate.

For example, the execution is delayed by 2 seconds and the fixed rate is 1 second.

Public class FixedRateDemo {public static void main (String [] args) {Timer timer = new Timer (); timer.scheduleAtFixedRate (new DoSomethingTimerTask ("FixedRateDemo"), 2000L, 1000L);}}

If you execute the program, you will find that it starts to be executed every 1 second after 2 seconds.

At this point, do you wonder why schedule has the same effect as scheduleAtFixedRate? why do you provide two methods? what's the difference between them?

2.3 differences between schedule and scheduleAtFixedRate

Before you understand the difference between the schedule and scheduleAtFixedRate methods, take a look at their similarities:

Task execution has not timed out, next execution time = last execution start time + period

Task execution timed out, next execution time = last execution end time

When the task execution does not time out, they are the last execution time plus the interval time to execute the next task. When the execution times out, it is executed immediately.

The difference between them is that the emphasis is different. The schedule method focuses on keeping the interval time stable, while the scheduleAtFixedRate method focuses more on maintaining the stability of the execution frequency.

2.3.1schedule focuses on keeping the interval stable.

The schedule method delays the scheduled tasks that follow it because of the delay of the previous task. The calculation formula is scheduledExecutionTime (n + 1) = realExecutionTime (n) + periodTime.

That is to say, if the execution time of the nth task is too long for some reason, and the systemCurrentTime > = scheduledExecutionTime (n + 1) after execution, then the n + 1 task will be executed immediately without waiting for intervals at this time.

The scheduledExecutionTime of the next n + 2 task (n + 2) becomes realExecutionTime (n + 1) + periodTime. This method pays more attention to keeping the interval stable.

2.3.2scheduleAtFixedRate keeps the execution frequency stable

When scheduleAtFixedRate repeatedly executes a task plan, the planned execution time for each execution of the task is initially set, that is, scheduledExecutionTime (nth) = firstExecuteTime + n*periodTime.

If, for some reason, the execution time of the nth task is too long, the systemCurrentTime > = scheduledExecutionTime (n + 1) after execution, then the period interval wait is not done at this time, and the n + 1 task is executed immediately.

The scheduledExecutionTime of the next n + 2 task (n + 2) is still firstExecuteTime+ (nasty 2) * periodTime, which is decided on the first time task is executed. To put it bluntly, this method pays more attention to maintaining the stability of the execution frequency.

If you use one sentence to describe the difference between schedule and scheduleAtFixedRate after a task timeout: schedule's strategy is to miss it, and then follow the new pace; scheduleAtFixedRate's strategy is to try to catch up with the original rhythm if you miss it.

2.4 defects in Timer

Timer timers can be timed (tasks are executed at specified times), delayed (tasks are delayed by 5 seconds), and tasks are executed periodically (tasks are executed every 1 second). However, Timer has some drawbacks. First of all, Timer's support for scheduling is based on absolute time, not relative time, so it is very sensitive to the change of system time.

Secondly, the Timer thread will not catch the exception. If the TimerTask throws an unchecked exception, it will cause the timer thread to terminate, and Timer will not resume the execution of the thread. It will mistakenly assume that the entire timer thread will be cancelled. At the same time, TimerTask that has been scheduled and not yet executed will no longer be executed, and new tasks cannot be scheduled. So if TimerTask throws an unchecked exception, Timer will behave unexpectedly.

3. JDK comes with ScheduledExecutorService

ScheduledExecutorService is a new scheduled task interface after JAVA 1.5. It is a scheduled task class based on thread pool. Each scheduled task is assigned to a thread in the thread pool to execute. In other words, tasks are executed concurrently and do not affect each other.

It is important to note that ScheduledExecutorService actually starts a thread only when the scheduled task is executed, and the rest of the time ScheduledExecutorService is out of the status of the polling task.

There are four main methods for ScheduledExecutorService:

ScheduledFuture schedule (Runnable command,long delay,TimeUnitunit); ScheduledFuture schedule (Callable callable,long delay,TimeUnitunit); ScheduledFuture scheduleAtFixedRate (Runnable command,long initialDelay,long period,TimeUnitunit); ScheduledFuture scheduleWithFixedDelay (Runnable command,long initialDelay,long delay,TimeUnitunit)

Among them, scheduleAtFixedRate and scheduleWithFixedDelay are more convenient and widely used in the implementation of timing programs.

The four interface methods defined in ScheduledExecutorService are almost the same as the corresponding methods in Timer, except that the scheduled method of Timer needs to pass in an abstract task of TimerTask. While the ScheduledExecutorService encapsulation is more detailed, there will be a layer of encapsulation inside the Runnable or Callable, encapsulating an abstract task class (ScheduledFutureTask) similar to TimerTask. Then pass in the thread pool and start the thread to perform the task.

3.1 scheduleAtFixedRate method

The scheduleAtFixedRate method, which performs a task on a specified frequency period. Definition and parameter description:

Public ScheduledFuture scheduleAtFixedRate (Runnable command, long initialDelay, long period, TimeUnit unit)

The corresponding meaning of the parameter: command is the thread being executed; initialDelay is the delayed execution time after initialization; period is the minimum interval between two starts of execution; unit is the timing unit.

Examples of use:

Public class ScheduleAtFixedRateDemo implements Runnable {public static void main (String [] args) {ScheduledExecutorService executor = Executors.newScheduledThreadPool (1); executor.scheduleAtFixedRate (new ScheduleAtFixedRateDemo (), 0, 1000, TimeUnit.MILLISECONDS) } @ Override public void run () {System.out.println (new Date () + ": task" ScheduleAtFixedRateDemo "is executed.) Try {Thread.sleep (2000L);} catch (InterruptedException e) {e.printStackTrace ();}

The above is the basic use of the scheduleAtFixedRate method, but when you execute the program, you will find that it is not executed at an interval of 1 second, but at an interval of 2 seconds.

This is because scheduleAtFixedRate executes tasks at intervals of period. If the task execution time is less than period, the last task will be executed at intervals of period and then the next task will be executed. However, if the task execution time is greater than period, the next task will start immediately after the last task is finished.

3.2 scheduleWithFixedDelay method

The scheduleWithFixedDelay method, which performs a task at specified frequency intervals. Definition and parameter description:

Public ScheduledFuture scheduleWithFixedDelay (Runnable command, long initialDelay, long delay, TimeUnit unit)

The corresponding meaning of the parameter: command is the executed thread; initialDelay is the delayed execution time after initialization; period is the interval between the end of the previous execution and the start of the next execution (interval delay time); unit is the timing unit.

Examples of use:

Public class ScheduleAtFixedRateDemo implements Runnable {public static void main (String [] args) {ScheduledExecutorService executor = Executors.newScheduledThreadPool (1); executor.scheduleWithFixedDelay (new ScheduleAtFixedRateDemo (), 0, 1000, TimeUnit.MILLISECONDS) } @ Override public void run () {System.out.println (new Date () + ": task" ScheduleAtFixedRateDemo "is executed.) Try {Thread.sleep (2000L);} catch (InterruptedException e) {e.printStackTrace ();}

The above is the basic use of the scheduleWithFixedDelay method, but when you execute the program, you will find that it is not executed at an interval of 1 second, but at an interval of 3 seconds.

This is because scheduleWithFixedDelay, no matter how long the task is executed, will wait for the last task to finish and then delay the delay to execute the next task.

4. Implementation of Quartz framework

In addition to the API that comes with JDK, we can also use open source frameworks such as Quartz.

Quartz is an open source project in the field of Job scheduling (Job scheduling). Quartz can be used alone or integrated with the spring framework, which is generally used in actual development. Using Quartz, you can develop one or more scheduled tasks, each of which can be executed separately, such as every 1 hour, at 10:00 on the first day of each month, at 5pm on the last day of each month, and so on.

A Quartz usually consists of three parts: a Scheduler, a JobDetail, and a trigger (Trigger, including SimpleTrigger and CronTrigger). The following is illustrated by a specific example.

4.1 Quartz Integration

To use Quartz, you first need to introduce the corresponding dependencies in the project's pom file:

Org.quartz-scheduler quartz 2.3.2 org.quartz-scheduler quartz-jobs 2.3.2

Define the Job that executes the task. Here, you need to implement the Job interface provided by Quartz:

Public class PrintJob implements Job {@ Override public void execute (JobExecutionContext jobExecutionContext) throws JobExecutionException {System.out.println (new Date () + ": task" PrintJob "is executed.) ;}}

Create Scheduler and Trigger and perform scheduled tasks:

Public class MyScheduler {public static void main (String [] args) throws SchedulerException {/ / 1, create scheduler Scheduler SchedulerFactory schedulerFactory = new StdSchedulerFactory (); Scheduler scheduler = schedulerFactory.getScheduler (); / / 2, create JobDetail instance and bind to PrintJob class (Job execution content) JobDetail jobDetail = JobBuilder.newJob (PrintJob.class) .withidentity ("job", "group") .build () / / 3. Build a Trigger instance and execute Trigger trigger = TriggerBuilder.newTrigger () .withIdentity ("trigger", "triggerGroup") .startNow () / / take effect immediately. Withschedule (SimpleScheduleBuilder.simpleSchedule (SimpleScheduleBuilder.simpleSchedule) .withIntervalInSeconds (1) / / every 1s. RepeatForever ()) .startNow (). / / always execute / / 4, Scheduler binds Job and Trigger, and executes scheduler.scheduleJob (jobDetail, trigger); System.out.println ("- scheduler start! -"); scheduler.start ();}}

If you execute the program, you can see that the scheduled task is executed every 1 second.

In the above code, Job is the interface of Quartz, and the implementation of business logic is realized by implementing this interface.

JobDetail binds the specified Job. Each time Scheduler schedules to execute a Job, it will first get the corresponding Job, then create the Job instance, and then execute the contents of execute () in the Job. After the task execution ends, the associated Job object instance will be released and cleared by JVM GC.

Trigger is the trigger of Quartz that tells Scheduler when to execute the corresponding Job. SimpleTrigger can perform one job task in a specified time period or multiple job tasks in a time period.

CronTrigger is very powerful and is a calendar-based job scheduling, while SimpleTrigger specifies intervals precisely, so it is more commonly used than SimpleTrigger,CroTrigger. CroTrigger is based on Cron expressions.

Examples of common Cron expressions are as follows:

It can be seen that CronTrigger based on Quartz can achieve very rich timed task scenarios.

5 、 Spring Task

Starting from Spring 3, Spring comes with a set of scheduled task tools Spring-Task, which can be regarded as a lightweight Quartz, which is very easy to use, does not require additional packages in addition to Spring-related packages, and supports annotations and configuration files. In general, in the Spring system, the functions provided by Spring can be used directly for simple scheduled tasks.

The form based on the XML configuration file is no longer introduced, just look at the implementation based on the annotated form.

It's very easy to use, just go to the code:

@ Component ("taskJob") public class TaskJob {@ Scheduled (cron = "0 03 * *?") Public void job1 () {System.out.println ("scheduled tasks defined by cron");} @ Scheduled (fixedDelay = 1000L) public void job2 () {System.out.println ("scheduled tasks defined by fixedDelay");} @ Scheduled (fixedRate = 1000L) public void job3 () {System.out.println ("scheduled tasks defined by fixedRate");}}

If you are in a Spring Boot project, you need to add @ EnableScheduling to the startup class to start the timing task.

In the above code, @ Component is used to instantiate the class, which has nothing to do with scheduled tasks. @ Scheduled specifies that the method is executed based on scheduled tasks, and the frequency of execution is determined by the expression specified by cron. The expressions used by CronTrigger above cron expressions are consistent. In contrast to cron, Spring also provides two forms of scheduled task execution, fixedDelay and fixedRate.

5.1 differences between fixedDelay and fixedRate

The differences between fixedDelay and fixedRate are similar to those in Timer.

FixedRate has a concept of timetable, T1, T2, T3 have already arranged the execution time when the task starts, such as 1 minute, 2 minutes, 3 minutes. When the execution time of T1 is more than 1 minute, it will cause T2 delay. When T1 is finished, T2 will execute immediately.

FixedDelay is relatively simple, indicating the interval between the end of the previous task and the start of the next task. No matter how long the task takes to execute, the interval between the two tasks is always the same.

5.2 disadvantages of Spring Task

Spring Task itself does not support persistence, nor does it launch an official distributed cluster model. It can only be implemented by developers manually expanding their business applications, which can not meet the needs of visualization and easy configuration.

6. Distributed task scheduling

The above scheduled task schemes are all for stand-alone machines and can only be used in a single JVM process. Now it is basically a distributed scenario, which requires a high-performance, highly available and scalable distributed task scheduling framework in the distributed environment.

6.1 Quartz distributed

First of all, Quartz can be used in distributed scenarios, but it needs to be based on the form of database locks. To put it simply, quartz's distributed scheduling strategy is an asynchronous strategy bounded by database. Each scheduler obeys an operation rule based on database lock to ensure the uniqueness of the operation, and the asynchronous operation of multiple nodes ensures the reliability of the service.

Therefore, the distributed scheme of Quartz only solves the problem of high availability of tasks (reducing single point of failure). The bottleneck of processing capacity is in the database, and there is no task fragmentation at the execution level, so it can not maximize the efficiency, so it can only rely on the shedulex scheduling level to do sharding, but it is difficult for the scheduling layer to do the optimal slicing combined with the actual running resources.

6.2 lightweight artifact XXL-Job

XXL-JOB is a lightweight distributed task scheduling platform. Characterized by platform, easy to deploy, rapid development, easy to learn, lightweight, easy to expand. The scheduling center and the actuator function complete the execution of the scheduled task. The dispatching center is responsible for unified scheduling, and the actuator is responsible for receiving and executing the scheduling.

For small and medium-sized projects, this framework is widely used.

6.3 other frameworks

In addition, there are Elastic-Job, Saturn, SIA-TASK and so on.

Elastic-Job is a distributed scheduling solution with high availability.

Saturn is a distributed task scheduling platform opened by VIPSHOP, which is modified on the basis of Elastic Job.

SIA-TASK is a reliable open source distributed task scheduling platform.

At this point, I believe you have a deeper understanding of "what are the ways to achieve scheduled tasks in Java?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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