Task scheduled tasks java

Interface ScheduledExecutorService

An ExecutorService that can schedule commands to run after a given delay, or to execute periodically.

The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution. The scheduleAtFixedRate and scheduleWithFixedDelay methods create and execute tasks that run periodically until cancelled.

Commands submitted using the Executor.execute(Runnable) and ExecutorService submit methods are scheduled with a requested delay of zero. Zero and negative delays (but not periods) are also allowed in schedule methods, and are treated as requests for immediate execution.

All schedule methods accept relative delays and periods as arguments, not absolute times or dates. It is a simple matter to transform an absolute time represented as a Date to the required form. For example, to schedule at a certain future date , you can use: schedule(task, date.getTime() — System.currentTimeMillis(), TimeUnit.MILLISECONDS) . Beware however that expiration of a relative delay need not coincide with the current Date at which the task is enabled due to network time synchronization protocols, clock drift, or other factors.

The Executors class provides convenient factory methods for the ScheduledExecutorService implementations provided in this package.

Usage Example

Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:

 import static java.util.concurrent.TimeUnit.*; class BeeperControl < private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public void beepForAnHour() < Runnable beeper = () ->System.out.println("beep"); ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); Runnable canceller = () -> beeperHandle.cancel(false); scheduler.schedule(canceller, 1, HOURS); > >

Источник

Java Concurrency: Scheduling Tasks to Execute After a Given Delay or Periodically

This Java Concurrency tutorial guides you how to schedule tasks to execute after a given delay or to execute periodically using a ScheduledExecutorService object in the java.util.concurrent package.

The ScheduledExecutorService interface defines convenient methods for scheduling tasks:

  • schedule (Callable callable, long delay, TimeUnit unit) : executes a Callable task after the specified delay.
  • schedule (Runnable command, long delay, TimeUnit unit) : Executes a Runnable task after a given delay.
  • scheduleAtFixedRate (Runnable command, long initialDelay, long delay, TimeUnit unit) : Executes a periodic task after an initial delay, then repeat after every given period. If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
  • scheduleWithFixedDelay (Runnable command, long initialDelay, long delay, TimeUnit unit) : Executes a periodic task after an initial delay, then repeat after every given delay between the termination of one execution and the commencement of the next.

long getDelay(TimeUnit unit)

The TimeUnit can be in NANOSECONDS, MILLISECONDS , SECONDS , MINUTES , HOURS , and DAYS .

And a ScheduledExecutorService object can be created via factory methods of the Executors utility class:

  • newScheduledThreadPool(int poolSize) : creates a thread pool that can schedule tasks to execute concurrently.
  • newSingleThreadScheduledExecutor() : creates a single-threaded executor that can schedule tasks to execute sequentially.
Читайте также:  Правила логических операций python

1. Scheduling a Task to Execute After a Given Delay

scheduler = newSingleThreadScheduledExecutor(); scheduler.schedule(task, delayTime, timeUnit);
import java.util.concurrent.*; /** * SimpleScheduledExecutorExample.java * * This program demonstrates how to schedule a task to execute after * a given delay. * * @author www.codejava.net */ public class SimpleScheduledExecutorExample < public static void main(String[] args) < ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); Runnable task = new Runnable() < public void run() < System.out.println("Hi!"); >>; int delay = 5; scheduler.schedule(task, delay, TimeUnit.SECONDS); scheduler.shutdown(); > >

As you can see, this program simply prints the message “Hi!” after a delay of 5 seconds, and then terminates.

And the following program demonstrates how to schedule a Callable task that returns a value:

import java.util.concurrent.*; /** * CallableScheduledExecutorExample.java * * This program demonstrates how to schedule a Callable task to execute after * a given delay, and wait for the result becomes available. * * @author www.codejava.net */ public class CallableScheduledExecutorExample < public static void main(String[] args) < ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); Callabletask = new Callable() < public Integer call() < // fake computation time try < Thread.sleep(5000); >catch (InterruptedException ex) < ex.printStackTrace(); >return 1000000; > >; int delay = 5; Future result = scheduler.schedule(task, delay, TimeUnit.SECONDS); try < Integer value = result.get(); System.out.println("value brush:java">scheduler = newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(task, initialDelayTime, periodicDelayTime, timeUnit);
import java.util.concurrent.*; /** * BeepClock.java * * This program demonstrates how to schedule a task to execute after * an initial delay, and repeat after a fixed rate. * * @author www.codejava.net */ public class BeepClock implements Runnable < public void run() < System.out.print("\007"); >public static void main(String[] args) < ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); Runnable task = new BeepClock(); int initialDelay = 4; int periodicDelay = 2; scheduler.scheduleAtFixedRate(task, initialDelay, periodicDelay, TimeUnit.SECONDS); >>

Notice that, with the execution of periodic tasks, do not call shutdown() on the executor because it causes the program to terminate immediately.

3. Scheduling Multiple Tasks to Execute Concurrently at a Fixed Delay

Submit a task to a scheduled thread pool executor with an initial delay time and the periodic delay time. Here’s the idiom:

scheduler = newScheduledThreadPool(); scheduler.scheduleWithFixedDelay(task1, initialDelayTime1, periodicDelayTime1, timeUnit); scheduler.scheduleWithFixedDelay(task2, initialDelayTime2, periodicDelayTime2, timeUnit); scheduler.scheduleWithFixedDelay(task3, initialDelayTime3, periodicDelayTime3, timeUnit);

For example, the following program uses a pool of 3 threads to schedule 3 countdown clocks to execute concurrently:

import java.util.concurrent.*; /** * ConcurrentScheduledTasksExample.java * * This program demonstrates how to schedule multple tasks to execute after * a given delay, and execute periodically after a fixed delay. * * @author www.codejava.net */ public class ConcurrentScheduledTasksExample < public static void main(String[] args) < ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3); CountDownClock clock1 = new CountDownClock("A"); CountDownClock clock2 = new CountDownClock("B"); CountDownClock clock3 = new CountDownClock("C"); scheduler.scheduleWithFixedDelay(clock1, 3, 10, TimeUnit.SECONDS); scheduler.scheduleWithFixedDelay(clock2, 3, 15, TimeUnit.SECONDS); scheduler.scheduleWithFixedDelay(clock3, 3, 20, TimeUnit.SECONDS); >>

Here, you can see 3 clocks A, B and C are scheduled to start at the same time, after an initial delay of 3 seconds, but their periodic delay times are different.

Here’s the code of the countdown clock:

/** * CountDownClock.java * * This class represents a coutdown clock. * * @author www.codejava.net */ public class CountDownClock extends Thread < private String clockName; public CountDownClock(String clockName) < this.clockName = clockName; >public void run() < String threadName = Thread.currentThread().getName(); for (int i = 5; i >= 0; i--) < System.out.printf("%s ->%s: %d\n", threadName, clockName, i); try < Thread.sleep(1000); >catch (InterruptedException ex) < ex.printStackTrace(); >> > >

scheduled multiple tasks

4. Cancelling a Scheduled Task

Future future = scheduler.scheduleWithFixedDelay(…); boolean mayInterruptIfRunning = true; future.cancel(mayInterruptIfRunning);

The boolean flag mayInterruptIfRunning specifies whether the thread executing the task should be interrupted or not.

For example, the following is an updated version of the program above. It stops the 3 clocks after 2 minutes, by using another scheduled task:

import java.util.concurrent.*; /** * ConcurrentScheduledTasksExampleWithCancel.java * * This program demonstrates how to schedule multiple tasks to execute after * an initial delay, and repeat after a fixed delay. * And all tasks are cancelled after a specified time. * * @author www.codejava.net */ public class ConcurrentScheduledTasksExampleWithCancel < public static void main(String[] args) < ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3); CountDownClock clock1 = new CountDownClock("A"); CountDownClock clock2 = new CountDownClock("B"); CountDownClock clock3 = new CountDownClock("C"); Futuref1 = scheduler.scheduleWithFixedDelay(clock1, 3, 10, TimeUnit.SECONDS); Future f2 = scheduler.scheduleWithFixedDelay(clock2, 3, 15, TimeUnit.SECONDS); Future f3 = scheduler.scheduleWithFixedDelay(clock3, 3, 20, TimeUnit.SECONDS); Runnable cancelTask = new Runnable() < public void run() < f1.cancel(true); f2.cancel(true); f3.cancel(true); >>; scheduler.schedule(cancelTask, 120, TimeUnit.SECONDS); > >

API References:

Other Java Concurrency Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Читайте также:  Конвектор html то pdf

Add comment

Comments

CodeJava.net shares Java tutorials, code examples and sample projects for programmers at all levels.
CodeJava.net is created and managed by Nam Ha Minh — a passionate programmer.

Copyright © 2012 — 2023 CodeJava.net, all rights reserved.

Источник

Java scheduled task framework

Make writing a habit together! This is the fifth day of my participation in the «Gold Digging Day New Plan · April More text Challenge». Click here for more details.

preface

The process in the development system will have the following requirements:

  • Generate order statistics report at dawn
  • Regularly push articles and send emails
  • Dynamic fetching of data updates every 5 minutes
  • Calculate the daily revenue of users and push it to users every night
  • .

We usually implement these requirements through scheduled task. We list some common scheduled task frameworks in Java.

Timing task framework

TimeTask

Since we started to learn Java, the first time to implement scheduled tasks is to use TimeTask, Timer internal use of the TaskQueue class to store scheduled tasks, which is a priority queue based on the minimum heap implementation. TaskQueue sorts tasks by their time to the next execution, ensuring that the tasks at the top of the heap are executed first.

public static void main(String[] args) < TimerTask task = new TimerTask() < public void run() < System.out.println(" current time: "+ new Date() + "n" +" thread.currentThread ().getName() "); >>; Timer timer = new Timer("Timer"); long delay = 5000L; timer.schedule(task, delay); System.out.println(" current time: "+ new Date() + "n" +" thread.currentThread ().getName() "); >Copy the code
Current time: Wed Apr 06 22:05:04 CST 2022N Thread name: main Current time: Wed Apr 06 22:05:09 CST 2022N Thread name: TimerCopy the code

According to the result, the scheduled task is executed 5 seconds later.

  • TimeTask tasks can only be executed serially. If one task is executed for a long time, other tasks will be affected
  • If an exception occurs during task execution, the task is stopped.

As time goes by, Java technology is constantly updated. ScheduledExecutorService is introduced to replace TimeTask.

ScheduledExecutorService

ScheduledExecutorService is an interface that has multiple implementation classes, more commonly used is ScheduledThreadPoolExecutor. While ScheduledThreadPoolExecutor itself is a thread pool, its internal use DelayQueue as task queue, and support the concurrent task execution.

public static void main(String[] args) throws InterruptedException < ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3); / / mission: once every 10 seconds to perform the executorService. ScheduleAtFixedRate (() - , 1, 10, TimeUnit.SECONDS); >Copy the code
  • Avoid using Executors to create a thread pool. The JDK thread pool uses a large queue, so OOM is likely to occur.
  • Scheduled tasks are based on JVM single machine memory and disappear once you restart them.
  • Cron expressions are not supported for rich scheduled tasks.
Читайте также:  Linking 2 cpp files

Spring Task

After learning Spring, I started to use Spring’s built-in Task. The Spring Framework comes with scheduled tasks and provides cron expressions to implement rich scheduled task configuration.

@EnableScheduling @Component public class SpringTask < private Logger logger = LoggerFactory.getLogger(SpringTask.class); private static final SimpleDateFormat dateFormat = new SimpleDateFormat( "HH:mm:ss"); /** * fixedRate: fixedRate execution. This command is executed every 5 seconds. */ @Scheduled(fixedRate = 5000) public void invokeTaskWithFixedRate() < logger.info("Fixed Rate Task : Current Time is <>", dateFormat.format(new Date())); > /** * fixedDelay: fixedDelay execution. Execution 2 seconds after the last call succeeded. */ @Scheduled(fixedDelay = 2000) public void invokeTaskWithFixedDelay() < try < TimeUnit.SECONDS.sleep(3); logger.info("Fixed Delay Task : Current Time is <>", dateFormat.format(new Date())); > catch (InterruptedException e) < logger.error("invoke task error",e); >> /** * initialDelay: initialDelay. The first execution of the task will be delayed by 5 seconds, and then it will be executed at fixed intervals of 5 seconds. */ @Scheduled(initialDelay = 5000, fixedRate = 5000) public void invokeTaskWithInitialDelay() < logger.info("Task with Initial Delay : Current Time is <>", dateFormat.format(new Date())); ** * Scheduled(cron = "0/5 ** **? ") public void invokeTaskWithCronExpression() < logger.info("Task Cron Expression: Current Time is <>", dateFormat.format(new Date())); >>Copy the code
2022-04-06 23:06:20.945 INFO 14604 -- [scheduling-1] com.fw.task.SpringTask: Task Cron Expression: Current Time is 23:06:20 2022-04-06 23:06:22.557 INFO 14604 -- [scheduling-1] com.fw.task.springTask: Task with Initial Delay : Current Time is 23:06:22 2022-04-06 23:06:22.557 INFO 14604 -- [scheduling-1] com.fw.task.springTask: Fixed Rate Task : Current Time is 23:06:22 2022-04-06 23:06:25.955 INFO 14604 -- [scheduling-1] com.fw.task.springTask: Fixed Delay Task : Current Time is 23:06:25 2022-04-06 23:06:25.955 INFO 14604 -- [scheduling-1] com.fw.task.springTask: Task Cron Expression: Current Time is 23:06:25 2022-04-06 23:06:27.555 INFO 14604 -- [scheduling-1] com.fw.task.springTask: Task with Initial Delay : Current Time is 23:06:27 2022-04-06 23:06:27.556 INFO 14604 -- [scheduling-1] com.fw.task.springTask: Fixed Rate Task : Current Time is 23:06:27Copy the code

@enablescheduling required to enable Scheduled tasks, @scheduled (cron = «0/5 * * * *?» ) Configure rules for scheduled tasks. Cron expressions support rich scheduled task configurations. For those unfamiliar, see cron.qqe2.com/

Easy to use, support a variety of complex scheduled task configuration

  • Based on the scheduled task in single-machine mode, the scheduled task disappears after the restart.
  • Scheduled tasks are executed in a single thread by default. To execute tasks in parallel, enable @enableAsync.
  • Scheduled tasks cannot be controlled without unified graphical task scheduling management

conclusion

The emergence of any technology has its value, there is no best technology, only the most appropriate. We need to choose the most appropriate technology for different needs without over-architecting. This article explains the techniques for implementing scheduled tasks in a stand-alone environment, and the next article will start with a distributed task framework.

Источник

Оцените статью