Study on Java--timer class

Source: Internet
Author: User

The Timer class is a threading facility that can be used to schedule a task to be executed once or periodically after a certain time or a certain period of time. This function is to be used in conjunction with the TimerTask. The TimerTask class is used to implement a task that is scheduled by the timer one or more executions.


The following example shows the use of the timer and the TimerTask class. The main function of the program is to periodically print the system's current time.

1. Create a subclass of TimerTask:

Import Java.util.date;import java.util.timer;import Java.util.timertask;import Java.util.regex.matcher;import Java.util.regex.pattern;import java.text.*;p ublic class MyTask extends timertask{public void run () {SimpleDateFormat Sdf=null;sdf=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss:SSS"); SYSTEM.OUT.PRINTLN ("System Current Time:" +sdf.format (New Date ()));}}
2. Build the Test class. To schedule a task:

Import Java.util.timer;public class Testtask {public static void main (string[] args) {Timer t=new timer (); MyTask mytask=new mytask (); T.schedule (MyTask, 1000, 2000);}}

The run instance effect is as follows:

System Current time: 2015-02-03 16:30:52:472
System Current time: 2015-02-03 16:30:54:472
System Current time: 2015-02-03 16:30:56:472
System Current time: 2015-02-03 16:30:58:472
System Current time: 2015-02-03 16:31:00:472
System Current time: 2015-02-03 16:31:02:472

Study on Java--timer class

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.