Java scheduled task scheduling tool details Timer

Summary of a.

1.1 Course Introduction

  • What is scheduled task scheduling?

    • Tasks that are automatically executed based on a given point in time, a given interval, or a given number of executions
  • Scheduled task scheduling tool in Java

    • Timer
    • Quartz
  • Difference:

    • Timer comes with it, Quartz comes with it
    • Different abilities that Timer can’t solve, Quartz can solve
    • The underlying mechanism, Quartz, is better than Timer, but Quartz is a bit harder to configure
  • Knowledge to prepare:

    • Using Timer,Quartz ->Java basics
    • Quartz ->Spring basics

1.2 introduction of the Timer

  • Definition of Timer:

    • One and only one background thread schedules multiple service threads at a fixed frequency
  • Main components:

    • Timer– >Time Task
  • Tool class details

1.3 Actual Combat

  • MyTimerTask.java
import java.util.TimerTask
public class MyTimerTask extends TimerTask{
	private String name;
	public MyTimerTask(String inputName){
		name=inputName;
	}
	@Override
	public void run(a){
		// Prints the contents of the current name
		System.out.println("Current exec name is:"+ name);
	}
	public String getName(a){
		return name;
	}
	public void setName(String name){
		this.name=name; }}Copy the code
  • Create MyTimer. Java
import java.util.Timer
public class MyTimer{
	public static void main(String[] args){
		1. Create a Timer instance
		Timer timer=new Timer();
		// create a MyTimerTask instance
		MyTimerTask myTimerTask=new MyTimeTask("No.1");
		//3. Invoke the business logic of myTimerTask through Timer
		// The first execution takes place two seconds after the current time, and every second after that
		timer.schedule(myTimerTask,2000L.1000L); }}Copy the code

The usage of timer function

2.1 Four uses of schedule

  • schedule(task,time):
    • Parameters:
      • Task -> Tasks to be scheduled
      • Time -> Time when the task is executed
    • Function:
      • Execute a task only once when the time is equal to or exceeds time

Perform once at a specific time;

  • suchedult(task,time,period)
    • Parameters:

      • Task: A task to be assigned
      • Time: indicates the time when the first task is executed
      • Period: indicates the interval for executing a task, in milliseconds
    • Function:

      • The task is executed for the first time when the time is equal to or exceeds time
      • Then the task is repeated every period millisecond
  • Actual code:

Using this schedule, it executes every 2000 milliseconds, starting with Calendar.getTime ();

  • schedule(task,delay)
    • Function:
      • Wait delay milliseconds before executing the task
    • Effect:

  • schedule(task,delay,period)
    • Function:
      • Wait for the first task to be executed after delay milliseconds
      • Then the task is repeated every period millisecond
    • Effect:

  • scheduleAtFixedRate(task,time,period)
    • Parameters:

      • Task: A task to be assigned
      • Time: indicates the time when the first task is executed
      • Period: indicates the interval for executing a task, in milliseconds
    • Function:

      • The task is executed for the first time when the time is equal to or exceeds time
      • Then the task is repeated every period millisecond
    • Effect:

  • scheduleAtFixedRate(task,delay,period)
    • Parameters:
      • Task: A task to be assigned
      • Delay: indicates the delay before executing a task, in milliseconds
      • Period: indicates the interval for executing a task, in milliseconds
    • Function:
      • Wait for the first task to be executed after delay milliseconds
      • Then the task is repeated every period millisecond
    • Effect:

Other important functions

3.1 Contents of this Section

  • TimerTask cancel (), scheduledExcetionTime ()
  • Cancel the Timer (), purge ()

3.2 Code Examples:

Here in the custom Timer code, use count to define a counter. When count reaches 3, execute cancel() to cancel the scheduled task.

3.3 scheduledExecutionTime ()

  • Function:
    • Returns the scheduled execution time of the last actual execution of this task
  • The return value:
    • The last scheduled time for this task execution occurred is long

Returns the execution time of the most recent task

  • The results are shown as follows:

3.4 Other functions of Timer

  • Cancel () -> This cancel is subordinate to the Timer and is different from the previous one
    • Action: Terminates this timer, discarding all currently scheduled tasks
  • The illustration is as follows:

Using timer.cancel causes timer timer=new timer (); The timer in terminates all its scheduled tasks.

3.5 purge ()

  • Return value: The number of tasks removed from the queue and removed from the current queue
  • Effect:

Purge () does not return the current number of tasks, but instead returns the number of cancelled tasks and removes the task from the current queue

4. Difference between Schedule and scheduleAtFixedRate

4.1 See the difference between the two cases

  • The first scheduled execution time is earlier than the current time (for example, the first task execution time is earlier than the current time).
  • The time required to execute the task exceeds the execution interval of the task (for example, we execute a scheduled task every 2 seconds, but each execution takes 3 seconds)

4.2 Specific Differences —- The time when the initial plan is executed is earlier than the current time

  • The schedule method
    • “Fixed-delay “: If the first execution time is delayed (earlier), the subsequent execution time is calculated according to the actual completion time of the last execution
  • ScheduleAtAFixedRate method
    • “Fixed-rate “: If the first execution time is delayed, the subsequent execution time is calculated according to the last start time, and the task will be executed multiple times to catch up with the progress. Therefore, the execution body in the TimerTask needs to consider synchronization.

4.2 Differences —- The time required for executing a task exceeds the task execution interval

  • The schedule method

    • The next execution time is relative to the point in time when the last execution is completed. Therefore, the execution time is constantly delayed
  • ScheduleAtFixedRate methods

    • The next execution time is relative to the last start point, so the execution time is generally not delayed, so there is concurrency;

ScheduleAtFixedRate is more accurate. However, if the time required to execute a task is longer than the task scheduling interval, two tasks are easy to be executed in parallel, that is, concurrency problems may occur.

  • Effect:

As can be seen, scheduleAtFixedRate is more accurate and executes every 2 seconds strictly according to the setting without being affected by the task time. However, scheduleAtFixedRate is delayed by 2 seconds according to the last successful execution time. Strictly speaking, there are essential differences between the two.

5. Comprehensive application of Timer function

5.1 Main Contents

  • By simulating the timing behavior of two robots to combine the main functions we have learned in front, let us deepen the understanding of these functions;

5.2 Realize two robots

  • The first robot will print the time and execution of the last plan every two seconds
  • The second simulated pouring water into a bucket until it was full;

5.4 Execution process of water filling robot

  • Here is:

5.5 Execution process of dancing robot

  • Here is:

5.6 Code Demonstration:

  • WaterRobot.java:
public class WaterRobot extends TimerTask{
	private Timer timer;
	// Maximum capacity is 5L
	private Integer bucketCapacity=0;
	public WaterRobot(Timer inputTimer){
		timer=inputTimer;
	}
	@Override
	public void run(a){
		Fill the water until the pail is full
		if(bucketCapacity<5){
			System.out.println("Add 1L water into the bucket!");
			bucketCapacity++;
		}else{
			// Stop executing when the water is full
			cancel();
			System.out.println("The waterRobot has been aborted");
			// Wait 2 seconds and terminate all contents of the timer
			try{
				Thread.sleep(2000);
			}catch(InterruptedException e){ e.printStackTrace(); } timer.cancel(); }}}Copy the code
  • Executor.java [Performing scheduled tasks]
public class Executor{
	public static void main(String[] args)throws InterruptedException{
		Timer timer=new Timer();
		// Get the current time
		Calendar calendar=Calendar.getInstance();
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("Current time is:" + sf.format(calendar.getTime()));
		timer.schedule(dr,calendar.getTime(),2000);
		timer.scheduleAtFixedRate(wr,calendar.getTime(),1000); }}Copy the code

Dancing robots can do it themselves;

Defects of Tiemr

6.1 Two types of congenital defects

  • The pitfalls of managing concurrent tasks
    • Timer has only one thread to execute the scheduled task. If there are multiple tasks and the task duration is too long, the execution effect is not as expected.
  • A defect when the task throws an exception
    • If the TimerTask throws a RuntimeException, the Timer stops all tasks

6.2 The use of Timer is restricted

  • Multi-task concurrent operation with high timeliness requirements
  • Scheduling of complex tasks

If you need both, you can use Quartz or an integrated distributed task scheduling framework.