This is the sixth day of my participation in the August Text Challenge.More challenges in August

A timed task simply means executing a method at a specified time and at a specified frequency. How do we implement this in Java?

So what we’re going to do today is basically start a thread, let it sleep for a while and run once and that’s how often we’re going to run, and we’re just going to write the business logic in the run method.

import java.util.Date; Public class ThreadTest {public static void main(String[] args) {final long timeInterval = 3000; Runnable runnable = new Runnable() { public void run() { while (true) { System.out.println("Task Run ... " + new Date()); try { Thread.sleep(timeInterval); } catch (InterruptedException e) { e.printStackTrace(); }}}}; Thread thread = new Thread(runnable); thread.start(); }}Copy the code

Using threads to perform timed tasks is at the heart of all cool timers. Here is a more convenient way to use a Timer.

Timer Timer can be simply understood as a tool that has only one background thread to schedule multiple service methods at a fixed frequency.

The implementation of a Timer task requires a Timer utility class and a TimerTask implementation class, which is used to write the logical code of the task.

Timer A Timer contains a queue of TimerTasks and a background thread of TimerThread. Note that the execution of tasks in Timer is dependent on this background thread.

Let’s take a look at some sample code

public class MyTask extends TimerTask{ private String name; public MyTask(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public void run() { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = sf.format(new Date()); System.out.println("exec MyTask ... The current time is: "+ format); System.out.println(this.name +" Executing! ") + sf.format(new Date())); } public static void main(String[] args) { Timer timer = new Timer(); TimerTask task1 = new MyTask("Tasks 1"); TimerTask task2 = new MyTask("Tasks 2"); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.SECOND, 3); Calendar calendar2 = Calendar.getInstance(); calendar2.add(Calendar.SECOND, 5); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = sf.format(new Date()); System.out.println(" format: "+ format); timer.schedule(task1, calendar1.getTime(), 3000L); timer.schedule(task2, calendar2.getTime(), 3000L); }}Copy the code

Timer-timerthread – TaskQueue – mytask-run Of course, the final method to be executed is the run method in our custom task. Because our custom task already inherits from TimerTask, this class already implements the Runnable interface.

A brief description of the different methods of starting tasks in timers. The difference between schedule and scheduleAtFixedRate methods?

There are two cases:

1 The initial execution time is earlier than the current time

Schedule: Perform tasks at intervals based on the current time.

ScheduleAtFixedRate: The number of times that a task is not executed in the past time is compensated when the task is executed for the first time.

2 The task execution time exceeds the task execution period

Schedule: The next execution time is based on the time when the last execution is completed. The execution may always be delayed.

ScheduleAtFixedRate: The time of the next execution is based on the time when the last execution starts. However, concurrency may occur.

There are two more ways to add to the cake. Cancel and Purge, wherein Cancel is divided into TimerTask cancellation for a single task and Timer cancellation for the entire Timer. The Timer call purge returns the number of canceled tasks.

The defect of the Timer

This is due to the fact that the Timer has only one thread of execution in the background.

2 Defects when a task throws an exception. If the TimerTask throws a RuntimeException, the Timer stops all tasks.

How to solve it? Java provides a utility class called ScheduledExecutorService that solves this problem.

In fact, the principle is very simple. In Timer, there is only one executing thread and multiple tasks are bound, so problems are easy to occur. The solution is to create a thread pool with multiple threads to complete multiple tasks.

But usually we want to use a Timer to do something, if it’s a simpler task, use a Timer, and I’ve seen it used in some projects.

For really complex timed tasks, such as those that require time, have a limit on the number of tasks and the number of times they can be executed, you can use a more complex timer framework called Quartz. For more on Quartz, listen next time…

By the way, Quartz has a background execution thread pool that allows multiple threads to perform tasks, so, you see, the core is multithreading.