Java Timer Task: To implement the function of timed task with Java Timer class _java

Source: Internet
Author: User
Tags garbage collection terminates

I. Overview

In Java to implement the functions of scheduled tasks, the main use of two classes, timer and TimerTask class. Where a timer is used to perform a specified task on a specified schedule in a background thread.

TimerTask an abstract class that represents a task that can be scheduled by a timer, and the specific code to execute is written in the Run method that TimerTask needs to be implemented.

Second, first look at one of the simplest examples

We use code to illustrate

Import Java.text.SimpleDateFormat;
Import java.util.Date;
Import Java.util.Timer;
Import Java.util.TimerTask;

public class Timerdemo {public
  static String GetCurrentTime () {
    Date date = new Date ();
    SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
    return Sdf.format (date);

  public static void Main (string[] args) throws Interruptedexception {
    System.out.println ("main start:" + GetCurrentTime ());
    Starttimer ();
    Thread.Sleep (1000*5); Hibernate 5 Seconds
    System.out.println ("Main end  :" +getcurrenttime ());
  }

  public static void Starttimer () {
    timertask task = new TimerTask () {
      @Override public
      void Run () {
        Sys Tem.out.println ("Task  run:" +getcurrenttime ());
      }
    ;
    Timer timer = new timer ();
    Timer.schedule (task, 0);
  }
}

To facilitate the printing of observation information, we added some printing information to the main method and called Thread.Sleep to let the main thread hibernate. Additionally, a GetCurrentTime method is added to the class to get the current date.

The above code, in the Starttimer method, first creates a TimerTask object (the task that will be executed by the timer), creates a timer object, and then invokes the schedule method of the Timer class. The Timer class has multiple schedule methods with different parameters. Here are the following:

public void Schedule (timertask task, long delay)

The meaning of this method is to perform a task task when the timer will delay delay (MS) time. If delay is negative or 0, the task is immediately performed. It is also a one-time task, and will not be repeated (or timed) to perform the task.

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

public void Schedule (timertask task, Date time)

The difference between this method and the above method is that the above method specifies that an extension is performed over a period of time, and this method is specified at a specific point in time. Note that the task will be executed immediately if the current time of the system has exceeded the time specified by the parameter times.

When we run the above code, we find that the program immediately prints 2 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 is 0, the task is executed immediately, so two statements are printed in the same time. You can change the incoming delay value to see the change of output information. After about 5 seconds (that is, sleep time), you continue to print 1 messages:

Main END:2016-01-13 22:23:23

The time to print the information and the above statement is 5 seconds, and sleep settings consistent, is also very reasonable.

But we will find a very interesting phenomenon, we will find that the process does not exit, when the main main thread is finished, which means that the timer to complete the task, even if there is no waiting for the task to be performed, the timer created in the background thread will not immediately exit. Viewed the relevant Java Doc documentation, explained that the timer thread does not actively exit and needs to wait for garbage collection, but the Java garbage collection is not controlled by the code itself, but by the virtual machine.

Studied the following, found in creating timer objects, and executing timer timer = new timer (); statement, the timer thread is created. That is, even if the above code does not have Timer.schedule (task, 0), this statement, the program will not exit. It's not reasonable to feel this way. The source code of the next timer class was studied again, and a constructor with a Boolean parameter was found:

Public Timer (Boolean Isdaemon)

As you can see from the parameter name, if the parameter value is true, the timer created by the timer is the daemon thread. The meaning of the daemon is that when all the worker threads in the Java process exit, the daemon automatically exits.

At this point we simply change the code to create the timer object in the example above: Timer timer = new timer (true);

After discovering that after running the program, when the main thread (the main thread is not the daemon thread, the worker thread) ends, the program exits, which means that the timer thread exits, which is the daemon thread that was created after the parameter true.

The problem is that in real-life scenarios, there are a lot of working threads running and the program doesn't just quit. What if you want the timer to quit or shut down immediately? This we introduce below.

Third, the withdrawal of the timer

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 present. Once the timer is terminated, its execution thread terminates and no more tasks can be scheduled according to it.

Note that this method is called within the Run method of the timer task invoked by this timer, and you can be absolutely sure that the task you are performing is the last task performed by this timer. This method can be called repeatedly, but the second and subsequent calls are invalid.

Let's look at one more example code:

 Import Java.text.SimpleDateFormat;
Import java.util.Date;
Import Java.util.Timer;
Import Java.util.TimerTask;

public class Timerdemo {public
  static String GetCurrentTime () {
    Date date = new Date ();
    SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
    return Sdf.format (date);

  public static void Main (string[] args) throws Interruptedexception {
    System.out.println ("main start:" + GetCurrentTime ());
    Timer timer = Starttimer ();
    Thread.Sleep (1000*5); Hibernate 5 Seconds
    System.out.println ("Main end  :" +getcurrenttime ());
    Timer.cancel ();
  }

  public static Timer Starttimer () {
    timertask task = new TimerTask () {
      @Override public
      void Run () {
        Sy Stem.out.println ("Task  run:" +getcurrenttime ());
      }
    ;
    Timer timer = new timer ();
    Timer.schedule (task, 0);
    return timer;
  }


Running the program is exactly the same as the output of an example above. The difference is when the main method finishes. The process will actively exit, meaning that 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 TimerTask run method, be sure to ensure that the task you want to perform is already started or executed, or if the task has not yet started executing. Calls cancel, all tasks are not executed. Like the code above,

For example, the above code, if we do not call the Cancel method in the main method, but rather in the Starttimer method Timer.schedule (task, 0); The statement is followed by a timer.cancel (), which, when run, will find that the timer task is not executed because it was canceled before it could be executed.

Iv. Perform tasks regularly

The above example, we are introducing a one-time task, that is, timer time is over, the completion of the task, will not be repeated after the execution. In practical applications, there are many scenarios that need to perform the same task regularly and repeatedly. This is done in two cases, one is to perform the task every other time, and the other is to perform the task at a certain (or some) point in time every day (or every week, month, etc.).

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

Import Java.text.SimpleDateFormat;
Import java.util.Date;
Import Java.util.Timer;
Import Java.util.TimerTask;

public class Timerdemo {public
  static String GetCurrentTime () {
    Date date = new Date ();
    SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
    return Sdf.format (date);

  public static void Main (string[] args) throws Interruptedexception {
    System.out.println ("main start:" + GetCurrentTime ());
    Starttimer ();
  }

  public static void Starttimer () {
    timertask task = new TimerTask () {
      @Override public
      void Run () {
        Sys Tem.out.println ("Task  run:" +getcurrenttime ());
        try {
          thread.sleep (1000*3);
        } catch (Interruptedexception e) {
          e.printstacktrace ();
        }}}
    ;
    Timer timer = new timer ();
    Timer.schedule (task, 1000*5,1000*10);
  }


Execute the above program, the output information as follows (because the timer does not stop, repeat the task, will continue to output, here only copied some of the previous output)

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 code above, we call the Timer.schedule (task, 1000*5,1000*10); The implication is that the task is delayed by 5 seconds and then repeated every 10 seconds. We look at the print time in the output information as expected. In addition, it can be seen that the interval is based on the start time of the task, which is not to wait 10 seconds after the execution of the task.

The timer class has two methods to implement this functionality, as follows:

public void Schedule (timertask task, long delay, long period) public

void Schedule (timertask task, Date Firsttime, Lon G period)

Our code above uses the first method. Two methods differ in the first execution time, the first is performed after the specified delay period (in milliseconds), and the second method is executed at a specified point in time.

At this point we consider the scenario where the execution of a task takes longer than the next wait time, what happens? We still look at the code:

 import java.text.SimpleDateFormat; import java.util.Date; import Java.util.Timer;

Import Java.util.TimerTask;
    public class Timerdemo {public static String GetCurrentTime () {Date date = new Date ();
    SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
  return Sdf.format (date); public static void Main (string[] args) throws Interruptedexception {System.out.println ("main start:" +getcurrentt
    IME ());
  Starttimer ();
        public static void Starttimer () {timertask task = new TimerTask () {@Override public void run () {
        SYSTEM.OUT.PRINTLN ("Task begin:" +getcurrenttime ());
        try {thread.sleep (1000*10);
        catch (Interruptedexception e) {e.printstacktrace ();
      } System.out.println ("Task End:" +getcurrenttime ());
    }
    };
    Timer timer = new timer ();
  Timer.schedule (task, 1000*5,1000*5); }
}

Compared to the previous code, we changed only 2 of the code and modified the print, one is to change the run method of sleep to 10 seconds, and the second is to change the task's execution cycle to 5 seconds. It is also said that the execution of a task takes longer than the interval of repeated tasks. Run the program, 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

As you can see, after each task completes, the next task is immediately executed. Because the time elapsed from the start of a task to the completion of a task has exceeded the interval between repetitions of the task, the execution is repeated.

V. Perform tasks periodically (repeat fixed-time point execution)

Let's implement a feature that performs a task at 1 o'clock in the morning every day, and this function is available in many systems, such as data backup, data statistics, and more time-consuming and resource-intensive tasks in this task. The code is as follows:

Import Java.text.SimpleDateFormat;
Import Java.util.Calendar;
Import Java.util.Date;
Import Java.util.Timer;

Import Java.util.TimerTask;
    public class Timerdemo {public static String GetCurrentTime () {Date date = new Date ();
    SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
  return Sdf.format (date); public static void Main (string[] args) throws Interruptedexception {System.out.println ("main start:" + Getcurren
    Ttime ());
  Starttimer ();
        public static void Starttimer () {timertask task = new TimerTask () {@Override public void run () {
        SYSTEM.OUT.PRINTLN ("Task begin:" + getcurrenttime ());
        try {thread.sleep (1000 * 20);
        catch (Interruptedexception e) {e.printstacktrace ();
      } System.out.println ("Task end:" + getcurrenttime ());
    }
    };
    Timer timer = new timer ();
  Timer.schedule (Task, Buildtime (), 1000 * 60 * 60 * 24); } private static Date buIldtime () {Calendar calendar = calendar.getinstance ();
    Calendar.set (Calendar.hour_of_day, 1);
    Calendar.set (calendar.minute, 0);
    Calendar.set (Calendar.second, 0);
    Date time = Calendar.gettime ();
      If Time.before (new Date ()) {//If the current time is already 1 o'clock in the morning, it needs to be added 1 days, otherwise the task will be executed immediately.
      Many systems often need to perform a task immediately when the system starts, but the following needs to be performed 1 o'clock in the morning every day.
    It's very simple to perform a single task (without the timer, just the code that executes the task) when the system initializes the session = Addday (time, 1);
  return time;
    private static date Addday (date date, int days) {Calendar Startdt = calendar.getinstance ();
    Startdt.settime (date);
    Startdt.add (Calendar.day_of_month, days);
  return Startdt.gettime ();

 }

}

Because it's 24 hours apart, you can't wait for the output to be observed.

Vi. Summary

This article describes the mechanism for using the Java Timer class to perform timed tasks. It can be seen that there are many ways to pay attention to. The example presented in this article, each timer corresponds to only one task.

This article covers most of the scenarios, but there are a few questions, such as how many tasks are included for a timer? Can I add a task again after the timer is canceled? What other methods are available in the Timer class? These questions, we'll go back to the posting introduction.

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

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.