java

Use Timer to schedule periodic tasks

The java.util.Timer and java.util.TimerTask classes can be used for many simple thread related tasks. Use them to perform an action either periodically or just once. As well, the first execution can be delayed to a specific time in the future.
The general guideline is :

if it may take a long time, or may block, use a Thread
if it is to be done later, or periodically, use TimerTask and Timer (which itself uses a background thread)
Example

Here, a task is performed once a day at 4 a.m., starting tomorrow morning.

import java.util.Timer;
import java.util.TimerTask;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;

public final class FetchMail extends TimerTask {

  /**
  * Construct and use a TimerTask and Timer.
  */
  public static void main (String... arguments ) {
    TimerTask fetchMail  = new FetchMail();

    //perform the task once a day at 4 a.m., starting tomorrow morning
    //(other styles are possible as well)
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(fetchMail, getTomorrowMorning4am(), fONCE_PER_DAY);
  }

  /**
  * Implements TimerTask's abstract run method.
  */
  public void run(){
    //toy implementation
    System.out.println("Fetching mail...");
  }

  // PRIVATE ////

  //expressed in milliseconds
  private final static long fONCE_PER_DAY = 1000*60*60*24;

  private final static int fONE_DAY = 1;
  private final static int fFOUR_AM = 4;
  private final static int fZERO_MINUTES = 0;

  private static Date getTomorrowMorning4am(){
    Calendar tomorrow = new GregorianCalendar();
    tomorrow.add(Calendar.DATE, fONE_DAY);
    Calendar result = new GregorianCalendar(
      tomorrow.get(Calendar.YEAR),
      tomorrow.get(Calendar.MONTH),
      tomorrow.get(Calendar.DATE),
      fFOUR_AM,
      fZERO_MINUTES
    );
    return result.getTime();
  }
}
 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s