Use and instance of timer in Java

Source: Internet
Author: User

A timer is used in an android project, that is, the program is not operated after five minutes, so that the program automatically exits.

Now I want to write a few common methods, taking the time bomb as an example.

1. Two seconds later, the bomb exploded.

// Define a timer two seconds later. The timer will pop up two seconds later.
Timer timer1 = new timer ();
Timer1.schedule (New timertask (){

@ Override
Public void run (){
System. Out. println ("bomb explosion ...");
}

},2000 );

2. A bomb exploded two seconds later, and then it exploded every second.

// The first bomb exploded two seconds later, and then exploded every second.
Timer timer2 = new timer ();
Timer2.schedule (New timertask (){

@ Override
Public void run (){
System. Out. println ("bomb explosion ...");
}

}, 2, 1 );

3. A serial bomb first explodes every two seconds, then once every four seconds, then two seconds, four seconds

// A serial bomb first explodes every two seconds, then once every four seconds, then two seconds, four seconds
Class mytimertask extends timertask {

@ Override
Public void run (){
Count = (count + 1) % 2;
System. Out. println ("bomb explosion ...");
New timer (). Schedule (New mytimertask (), 2000 + 2000 * count );
}

}
Timer timer3 = new timer ();
Timer3.schedule (New mytimertask (), 2000 );

4. Let the explosion happen at a certain time on a certain day

Timer timer4 = new timer ();
Timer4.schedule (task, time );

The task is a timertask.

Timer is of the date type.

5. Explosion at some point every day

Timer4.schedule (task, delay, period );
Timer4.scheduleatfixedrate (task, firsttime, period );

Use one of the methods.

Period is of the long type.

Of course, 4th and 5th may be used by a third party and can be directly configured, such as quartz.

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.