Traditional Timer Technology Timer

Source: Internet
Author: User

This article is a study note for Zhang Xiaoxiang Java concurrency Course.
The Java.util.Timer timer is actually a thread that is scheduled to be owned by the Timertasks.
A timertask is actually a class that has a run method, and the code that needs to be executed regularly is put into the Run method body, and timertask is typically created in the form of an anonymous class.

Let's take a look at the timer's API documentation

It has some of the following methods

Cancel, canceling the task

Purge, remove the canceled task



Schedule (timertask task, long delay)The task is executed after a delay of milliseconds.
And look at TimerTask.
Public abstract class TimerTask extends Object
Implements Runnable
Even if it is a guess, we should also be able to guess the key to TimerTask is inside the Run method.
OK, let's see an example.
Import Java.util.date;import Java.util.timer;import Java.util.timertask;public class TraditionalTimerTest2 {        public static void Main (string[] args) {    new Timer (). Schedule (new TimerTask () {            @Override public            void Run () {                System.out.println ("bombing!");            }        , +);  After 1 seconds execute the Run method                //The main thread continues to run every 1 seconds output now the second number        while (true) {            System.out.println (new Date (). getseconds ());            try {                thread.sleep;            } catch (Interruptedexception e) {                //TODO auto-generated catch block                E.printstacktrace ();}}}    


Run results
----------running Java----------
29
bombing!
30
31
32
33
34
35
36
37
38
39
40
41
42
Schedule (timertask task, long delay, long period)What does this do? The task task starts after delay milliseconds and then executes every period milliseconds
Some of the code is as follows:
    public static void Main (string[] args) {    new Timer (). Schedule (new TimerTask () {            @Override public            void Run () {                System.out.println ("bombing!");            }        , 3000,1000);        ....}
Results
----------running Java----------
5
6
7
bombing!
8
bombing!
9
bombing!
10
bombing!
11
bombing!
Of course there is another way to achieve the above effect
    public static void Main (string[] args) {        class Mytimertask extends timertask{                        @Override public            void Run () {
   system.out.println ("bombing!");                New Timer (). Schedule (New Mytimertask (), +);            }        }                New Timer (). Schedule (New Mytimertask (), n);    }
You should be able to guess the results.
If I let the bomb explode two seconds at a time, and then explode every three seconds, then two seconds, then three seconds ...
How is it?
public class TraditionalTimerTest4 {    private static int count = 0;    public static void Main (string[] args) {        class Mytimertask extends timertask{                        @Override public            void Run () {
   count = (count+1)%2;                System.out.println ("bombing!");                New Timer (). Schedule (New Mytimertask (), 2000+1000*count);            }        }        New Timer (). Schedule (New Mytimertask (), n);        .....    }}

Run results
----------running Java----------
17
18
19
20
Bombing
21st
22
Bombing
23
24
25
Bombing
26
27
Bombing
28
29
30
Bombing
31
32
Bombing
33
34
35

And of course there's a way
Import Java.util.date;import java.util.timer;import java.util.TimerTask;    public class MyTimerTask2 extends timertask{                    @Override public        void Run () {            System.out.println ("Bombing!2" );            New Timer (). Schedule (New MyTimerTask3 (), n);        }    } Import Java.util.date;import java.util.timer;import java.util.TimerTask;    public class MyTimerTask3 extends timertask{                    @Override public        void Run () {            System.out.println ("bombing!3 ");            New Timer (). Schedule (New MyTimerTask2 (), +);        }    }


There's one of these two classes that everyone should know how to write.
Schedule (timertask task, Date time)Schedule (timertask task, Date Firsttime, long period)
The above method is a time execution task, the following is Firsttime execution once, every period milliseconds to execute again.

If I want the bomb to explode 8:00 every day. You know how to write it? Firsttime designated as tomorrow morning, period for 24*86400*1000. Ok?


The difference between schedule and scheduleatfixedrate is that if you specify that the time to start execution is before the current system run time, Scheduleatfixedrate will execute the elapsed time as a cycle, and schedule will not count the past time.

Like what
SimpleDateFormat ftime = new SimpleDateFormat ("Yyyy/mm/dd HH:mm:ss");  Date D1 = Ftime.parse ("2005/12/30 14:10:00");   T.scheduleatfixedrate (New TimerTask () {public   void run ()   {       System.out.println ("This is the task you Do6");   }  },d1,3*60*1000);

The interval is 3 minutes, the specified start time is 2005/12/30 14:10:00, if I run this program at 14:17:00, it will be printed 3 times

This is the task you do6//14:10
This is the task you do6//14:13
This is the task you do6//14:16

Also note that the next execution is at 14:19 instead of 14:20. This means that the timing starts from the specified start time, not from the execution time.

But above if using the schedule method, the interval is 3 minutes, the specified start time is 2005/12/30 14:10:00, then at 14:17:00 minutes to execute the program, immediately execute the program once. And the next execution time is 14:20, not the period starting from 14:10 (14:19).


What if I want to perform a task at 8 on the second Sunday of every month?

Find Quartz It's a library of scheduling tasks

I have not used it, when needed to learn is OK.

We don't need to know about these things, we just need to know where to look for answers when we encounter certain problems.

There are tens of thousands of drugs in the world, we will have hundreds of thousands of kinds of diseases in our life, we can not remember the use of all the methods of medicine;

The best thing is that we know that when we have some kind of disease, we should go to some kind of medicine. Take the medicine and slowly learn its usage is OK.

Afraid of fear, when you get sick, you do not know what kind of medicine to eat!


Reference http://batitan.iteye.com/blog/253483
http://blog.csdn.net/weidan1121/article/details/527307

Traditional Timer Technology Timer

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.