Timer usage in Java

Source: Internet
Author: User

The Java timer uses the Timer class timer in the Java.util package. When used, instantiate and then use the schedule (timertask task, long delay) method of the instance to set the specified task tasks to run after the specified delayed delay. Timer Task Class TimerTask is an abstract class that inherits and overrides its run () method to implement detailed tasks.

Schedule (timertask task, Date time) sets the task to run at a specified time.

The Cancel () method ends the timer.

The schedule (timertask task, long delay, long period) method specifies that task tasks perform a fixed-delay peroid operation after specifying a delayed delay.

The Scheduleatfixedrate (timertask task, long delay, long period) method sets the specified task tasks to run at a fixed frequency peroid after the delay is specified.

To implement a timed task, using the timer and TimerTask classes in Java makes it easy to implement real-time call handling functions. These two classes are convenient to use and can complete most of the needs of our timers.

Look at a simple example:

Import java.io.IOException;
Import Java.util.Timer;

public class Timertest {

public static void Main (string[] args) {
Timer timer = new timer ();
Timer.schedule (New MyTask (), 1000, 2000);//Run this task in 1 seconds, 2 seconds at a time, assuming that a data parameter is passed to run the task at a fixed time.
while (true) {//This is used to stop this task, otherwise the task has been run cyclically.
try {
int ch = System.in.read ();
if (ch-' C ' ==0) {
Timer.cancel ();//Use this method to exit a task
}
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}

Static class MyTask extends java.util.timertask{
@Override
public void Run () {
TODO auto-generated Method Stub
System.out.println ("________");
}
}
}

Timer usage in Java

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.