Java timer usage

Source: Internet
Author: User

 

Java timer usage

 

The timer class timer is in the Java. util package.
In use, the instance is first instantiated, and then the schedule (timertask task, long delay) method of the instance is used to set the specified task to be executed after the specified delay.

The timer task class timertask is an abstract class that inherits and overwrites its run () method to implement specific tasks.

Schedule (timertask task, date time) sets the task to be executed at the specified time.
The schedule (timertask task, long delay, long period) method is used to set the scheduled task to execute a fixed-latency peroid after the specified delay.
The scheduleatfixedrate (timertask task, long delay, long period) method sets a fixed frequency of peroid execution for a specified task after a specified delay of delay.
The cancel () method ends this timer.

To implement a scheduled task, using the timer and timertask classes in Java can easily call processing functions in real time.
These two classes are very convenient to use and can fulfill the vast majority of timer needs.

 

Package COM. demo. timer; import Java. io. ioexception; import Java. util. timer;/*** Java timer usage **/public class timertest {public static void main (string [] ARGs) {timer = new timer (); // execute this task after 1 second, every 2 seconds. If you pass a data parameter, You can execute this task at a fixed time. timer. schedule (New mytask (), 1000,200 0); // This is used to stop this task, otherwise it will be executed cyclically while (true) {try {int CH = system. in. read (); If (CH-'c' = 0) {system. out. println ("Stop task"); timer. cancel (); // exit the task using this method} catch (ioexception e) {e. printstacktrace () ;}}/ *** assume an internal class */static class mytask extends Java. util. timertask {public static int I = 0; @ overridepublic void run () {I ++; system. out. println ("________" + I );}}}

 

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.