Import Java.util.timer.*class Timertaskexample extends TimerTask {public void run () {println new Date () }}int delay =//delay for 5 sec.int period =//Repeat every sec. Timer timer = new timer () Timer.scheduleatfixedrate (New Timertaskexample (), delay, period)
Output:
Thu Apr 05:54:02 CST 2015Thu Apr 05:54:03 CST 2015Thu Apr 05:54:04 CST 2015Thu Apr 05:54:05 CST 2015Thu Apr 02 05:54:06 CST 2015Thu Apr 05:54:07 CST 2015Thu Apr 05:54:08 CST 2015Thu Apr 05:54:09 CST 2015Thu Apr 02 05:54:10 CST 2015Thu Apr 05:54:11 CST 2015Thu Apr 05:54:12 CST 2015
Java version:
Import Java.util.timer;import Java.util.date;class Timertasktest extends Java.util.TimerTask {@Overridepublic void run () {System.out.println (New Date ());}} public class Test {public static void main (string[] args) {int delay = 5000; Delay for 5 sec.int period = 1000; Repeat every sec. Timer timer = new timer (), Timer.schedule (New Timertasktest (), delay, period);}}
Instructions for using the Timer and TimerTask:
java.util.timer timer = new Java.util.Timer (true); // true shows that this timer runs in daemon mode (priority low, // program End Timer also ends automatically), note that There is also a timer class in the javax.swing // package, if you use the Swing package in import, // you should pay attention to the name conflict. timertask task = new timertask () { public void run () { ... //the code that needs to be executed every time you put it in here. } }; //The following are several ways to schedule a task: timer.schedule (task, time); // Time is a date type: Executed once at the specified times. timer.schedule (task, firsttime, period); // firsttime is a date type, period is long // executes once every period milliseconds from the firsttime moment onwards. timer.schedule (Task, delay) // delay is a long type: The timer.schedule is executed once from now on delay milliseconds ( Task, delay, period) // delay is long,period to long: From now on delay milliseconds, every period // milliseconds.
Note: timer.schedule (task, delay, period) and timer.scheduleatfixedrate (task, delay, period) are different.
The period of the former is relative to the previous execution time. The latter period are strictly followed by the first execution time and so on.
Sample Timer and TimerTask in groovy