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