Java scheduled task: use the Java timer class to realize the function of executing tasks regularly

1、 Overview

To realize the function of executing tasks regularly in Java, two classes are mainly used, timer and TimerTask. Timer is used to execute the specified task in a background thread according to the specified plan.

TimerTask is an abstract class. Its subclasses represent a task that can be scheduled by timer. The specific code to be executed is written in the run method that TimerTask needs to be implemented.

2、 Let's start with the simplest example

We use code to illustrate

In order to print the observation information, we add some print information to the main method and call thread Sleep lets the main thread sleep. In addition, a getcurrenttime method for obtaining the current date is added to the class.

The above code, in the startTimer method, first creates a TimerTask object (the task to be executed by the timer), then creates a Timer object, then calls the schedule method of the Timer class. Timer class has several schedule methods with different parameters.

The meaning of this method is that the timer will delay the execution of the task task after the delay (MS). If the delay is negative or 0, the task will be executed immediately. In addition, it is a one-time task, and the task will not be executed repeatedly (or regularly) in the future.

For the timer class, a method with the same function is provided, as follows:

The difference between this method and the above method is that the above method specifies to postpone the execution for a period of time, and this method specifies to execute at a specific time point. Note that if the current time of the system has exceeded the time specified by the parameter time, the task will be executed immediately.

When running the above code, we found that the program immediately prints two messages similar to the following:

main start:2016-01-13 22:23:18 task run:2016-01-13 22:23:18

Because the value of the delay parameter passed to the schedule method here is 0, the task will be executed immediately, so the printing time of the two statements is the same, which should be. You can change the incoming delay value to see the change of output information. After about 5 seconds (i.e. sleep time), continue to print a message:

main end:2016-01-13 22:23:23

The time of printing information is 5 seconds different from the above statement, which is consistent with the sleep setting, which is also very reasonable.

But we will find a very interesting phenomenon. We will find that the process will not exit. At this time, the main thread has ended, which means that after the timer completes the task, even if there are no tasks to be executed later, the background thread created in the timer will not exit immediately. After checking the relevant Java DOC documents, I explained that the timer thread will not quit voluntarily and needs to wait for garbage collection, but the Java garbage collection can not be controlled by the code itself, but by the virtual machine.

It is found that when creating a timer object and executing timer timer = new timer(); Statement, the timer thread is created. That is, even if the above code does not have a timer schedule(task,0); This statement, the program will not exit. I don't think this is reasonable. After studying the source code of the following timer class, it is found that it also has a constructor with Boolean parameters:

As can be seen from the parameter name, if the parameter value is true, the timer thread created by timer is a daemon thread. The meaning of daemon thread is that when all working threads in the java process exit, the daemon thread automatically exits.

At this time, we just need to change the code for creating timer object in the above example to: timer timer = new timer (true);

It is found that after running the program, the program will exit when the main thread (the main thread is not a daemon thread, but a worker thread) ends, that is, the timer thread also exits. It indicates that after adding the parameter true, it is a daemon thread.

But the problem is that in a real application scenario, there are many working threads running, and the program will not exit casually. What if you want the timer to exit or close immediately? This is described below.

3、 Timer exit

The timer class provides a cancel method to cancel the timer. Calling the cancel method terminates the timer and discards all currently scheduled tasks. This does not interfere with the currently executing task (if any). Once the timer is terminated, its execution thread will also terminate and no more tasks can be scheduled according to it.

Note that calling this method within the run method of the timer task called by this timer can absolutely ensure that the task being executed is the last task executed by this timer. This method can be called repeatedly; However, the second and subsequent calls are invalid.

Let's take another example code:

Run the program, which is exactly the same as the output of the above example. The difference is that when the main method ends. The process will automatically exit, that is, the timer thread has been closed.

Because we called the cancel method in the main method. Note that if you do not call the cancel method in the run method of TimerTask, you must pay attention to it. Make sure that the task you want to execute has been executed or executed, otherwise, if the task has not been executed yet. If cancel is called, all tasks will not be executed. Like the code above,

For example, the above code, if we do not call the cancel method in the main method, but in the startTimer method timer. schedule(task,0); Add timer after the statement cancel(); Statement. After running, you will find that the timer task will not be executed because it is cancelled and aborted before execution.

4、 Perform tasks regularly

In the above example, we introduce a one-time task, that is, when the timer time is up, the task will not be repeated later. In practical applications, there are many scenarios that need to perform the same task regularly and repeatedly. This is also divided into two situations: one is to perform tasks at regular intervals, and the other is to perform tasks at a fixed time point (or several) every day (or every week, every month, etc.).

Let's take a look at the first case, an example of implementing the same task every 10 seconds. The code is as follows:

Execute the above program, and the output information is as follows (because the timer does not stop, repeat the task, and it will continue to output. Here, only some previous outputs are copied)

main start:2016-01-14 08:41:14 task run:2016-01-14 08:41:19 task run:2016-01-14 08:41:29 task run:2016-01-14 08:41:39 task run:2016-01-14 08:41:49 task run:2016-01-14 08:42:00 task run:2016-01-14 08:42:10 task run:2016-01-14 08:42:20 task run:2016-01-14 08:42:30 task run:2016-01-14 08:42:40

In the above code, we call timer schedule(task,1000*10); This means that the task is delayed for 5 seconds and then repeated every 10 seconds. We observe that the printing time in the output information is the same as expected. In addition, it can be seen that the interval is calculated from the start time of task execution, that is, it does not wait for 10 seconds after task execution is completed.

Timer class has two methods to realize such functions, as follows:

Our code above uses the first method. The difference between the two methods lies in the first execution time. The first method is executed after a specified delay period of time (in milliseconds); the second method is executed at a specified time point.

At this time, we consider the following scenarios. What happens if the execution time of a task exceeds the next waiting time? Let's look at the code:

Compared with the previous code, we only changed the code in two places and modified the next print. One is to change the sleep in the run method to 10 seconds, and the other is to change the execution cycle of the task to 5 seconds. In other words, the execution time of the task exceeds the interval of repeated execution of the task. Run the program, and the previous output is as follows:

main start:2016-01-14 09:03:51 task begin:2016-01-14 09:03:56 task end:2016-01-14 09:04:06 task begin:2016-01-14 09:04:06 task end:2016-01-14 09:04:16 task begin:2016-01-14 09:04:16 task end:2016-01-14 09:04:26 task begin:2016-01-14 09:04:26 task end:2016-01-14 09:04:36 task begin:2016-01-14 09:04:36 task end:2016-01-14 09:04:46 task begin:2016-01 -14 09:04:46 task end:2016-01-14 09:04:56

It can be seen that after each task is completed, the next task will be executed immediately. Because the time from the beginning of task execution to task completion has exceeded the interval between task repetition, it will be repeated.

5、 Execute tasks regularly (repeat at fixed time points)

Let's implement such a function. We execute a task at 1 a.m. every day. This function is available in many systems, such as completing time-consuming and resource consuming tasks such as data backup and data statistics. The code is as follows:

Because it is executed every 24 hours, it is impossible to wait for the observation output.

6、 Summary

This paper introduces the mechanism of how to execute timed tasks using java timer class. It can be seen that there are still many methods that need attention. In the example introduced in this article, each timer corresponds to only one task.

The content introduced in this article can meet most application scenarios, but there are still some problems, such as how many tasks are included in a timer? Can I add a task again after the timer is cancelled? What other methods are available in the timer class? These problems will be introduced in the following blog post.

Original link: http://www.cnblogs.com/51kata/p/5128745.html

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>