Using TimerTask to Do Stuff at Intervals

     

If you've ever used a UNIX cron job, you're used to needing to do stuff at timed intervals. Say you want to gzip the log files and move them in an archive every night at 3 a.m. Or maybe you need to start a process that will go out and check a server for some kind of update, and you want to check it every hour .

I once wrote an application that received user signups, and wrote them to a file. There were a lot of signups every day, but there wasn't a need to act upon them immediately. So the client asked that every hour we would do some junk to the data and then transfer it over to their AS/400 via FTP. Then they would do some junk to the data over there, and my app would check every couple of hours to see if they had written out the new file, and if they had, fetch the whole thing. So, anyway, if you need to do something repeatedly, or start doing it after a delay, java.util.TimerTask is the ticket.

We'll look at both ways in the upcoming pages.

Scheduling a Task to Start After a Delay

There are a few different ways to use the TimerTask to schedule and repeat jobs. You can specify to delay the start of a task using a millisecond delay, or by specifying a date.

DelayTask.java
 

 package net.javagarage.tasks; import java.util.Timer; import java.util.TimerTask; /**  * Uses java.util.Timer schedules the task to start  * running three seconds after it's instantiated.  * @author eben hewitt  */ public class DelayTask { //hold it in a member so everybody can get to it protected Timer timer; //public constructor accepts the //number of milliseconds to delay before running //the task public DelayTask(int msDelay){ timer = new Timer(); //pass the schedule method the task that you want //to start, and the delay timer.schedule(new PrintOutTask(), msDelay); } //using inner class to get to the timer member //make it extend TimerTask class PrintOutTask extends TimerTask{ //we must implement the run() method public void run(){ //do the work here... System.out.println("Task is doing some work..."); //terminates and discards this timer timer.cancel(); System.out.println("All done."); } } public static void main(String[] args) { System.out.println("Scheduling task..."); new DelayTask(3000); System.out.println("The task has been scheduled."); } } 

The output initially is

 

 Scheduling task... The task has been scheduled. 

And then after a three second delay, the following is printed:

 

 Task is doing some work... All done. 

So the main thing that you need to do to schedule a task is as follows :

  • Create a class that extends TimerTask.

  • In that class, implement the inherited run() method, and do your work in there.

  • Create an instance of the Timer class. This starts a new thread.

  • Create an instance of the class that extends TimerTask (here, called PrintOutTask, because his job is to print out statements).

  • Schedule the task to start.

  • When you need to stop the task, call the timer's cancel() method.

You can schedule a task to begin after a delay, but you can also schedule it to start at a certain moment in time. Let's try that now.

Scheduling a Task to Start at a Certain Moment in Time

In the following code, we do essentially the same thing that we did earlier, but this time we specify exactly when we want it to run. You do this by using a different constructor of the TimerTask class.

StartAtTimeTask.java
 

 package net.javagarage.tasks; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; /**  * <p>  * Starts a task at a particular date/time.  * <p>  * Note that if the scheduled execution time is  * in the past, the task will start immediately.  * @author eben hewitt  */ public class StartAtTimeTask { public static void main(String[] args) { int delay = 2000; //2 seconds int period = 5000; //5 seconds //Get the Date corresponding to 3:58:00 pm today.   Calendar calendar = Calendar.getInstance();   calendar.set(Calendar.HOUR_OF_DAY, 15);   calendar.set(Calendar.MINUTE, 58);   calendar.set(Calendar.SECOND, 0); Date scheduledDate = calendar.getTime(); System.out.println("Task scheduled for " +            scheduledDate); Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run(){ System.out.println("The task ran at " + new Date()); } }, scheduledDate); } } 

The output shows that the task ran at a different time than the task was scheduled for, because that time was in the past. Otherwise, it would have printed 15:58:00 as expected.

 

 Task scheduled for Fri Jan 02 15:58:00 GMT-07:00 2004 The task ran at Fri Jan 02 15:59:08 GMT-07:00 2004 

Note that the program will continue running after the job is scheduled, and will keep running. We don't call the cancel() method. That's because normally the reason you schedule a task is so that the scheduling thread can be alive to know when it is supposed to do its work.

Scheduling a Task that Runs Repeatedly at a Given Interval

As with my FTP application mentioned previously, you often need to check for a status or get an updated file or post some new data at a given interval, say every hour. The following code shows how to do this.

RepeatingTask.java
 

 package net.javagarage.tasks; import java.util.Timer; import java.util.TimerTask; /**  * <p>  * Demonstrate how to use a Timer that  * causes some code to execute repeatedly  * at a given interval.  * @author eben hewitt  */ public class RepeatingTask { public static void main(String[] args) { int delay = 2000; //delay for 2 seconds int interval = 60000; //repeat every minute Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { // This is where you do the work System.out.println("Current date and time is: " + new java.util.Date()); } //end run method of our anonymous TimerTask }, delay, interval); //end call to scheduler } } 

When I run it, it outputs the following, and would keep outputting forever until the VM is shut down or something more colossal happens like the world blows up, which has the effect of shutting down the VM.

 

 Current date and time is: Fri Jan 02 14:43:09 GMT-07:00 2004 Current date and time is: Fri Jan 02 14:44:09 GMT-07:00 2004 Current date and time is: Fri Jan 02 14:45:09 GMT-07:00 2004 

Here are all of the overloaded Timer methods that are available:

 

 schedule(TimerTask task, long delay, long period) schedule(TimerTask task, Date firstTime, long delay) schedule(TimerTask task, Date time) schedule(TimerTask task, long delay, long period) scheduleAtFixedRate(TimerTask task, long delay,     long period) scheduleAtFixedRate(TimerTask task, Date firstTime,     long period) cancel() purge() 



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net