Java Timer and TimerTask Example
In this tutorial we are going to see how you can use
Timer
and TimerTask
classes of the java.util
package in order to schedule the execution of a certain process.
The
Timer
class uses several flexible methods to make it possible to to schedule a task to be executed at a specific time, for once or for several times with intervals between executions.OUTPUT:package com.javanotes2all.java.date; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class TimerTaskExample extends TimerTask { @Override public void run() { System.out.println("Start time:" + new Date()); doSomeWork(); System.out.println("End time:" + new Date()); } // simulate a time consuming task private void doSomeWork() { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String args[]) { TimerTask timerTask = new TimerTaskExample(); // running timer task as daemon thread Timer timer = new Timer(true); timer.scheduleAtFixedRate(timerTask, 0, 10 * 1000); System.out.println("TimerTask begins! :" + new Date()); // cancel after sometime try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } timer.cancel(); System.out.println("TimerTask cancelled! :" + new Date()); try { Thread.sleep(30000); } catch (InterruptedException e) { e.printStackTrace(); } } }
Start time:Fri Feb 08 14:13:58 IST 2013
TimerTask begins! :Fri Feb 08 14:13:58 IST 2013
End time:Fri Feb 08 14:14:09 IST 2013
Start time:Fri Feb 08 14:14:09 IST 2013
End time:Fri Feb 08 14:14:19 IST 2013
Start time:Fri Feb 08 14:14:19 IST 2013
TimerTask cancelled! :Fri Feb 08 14:14:19 IST 2013
End time:Fri Feb 08 14:14:29 IST 2013
0 comments:
Post a Comment