Colt 1.0.2

edu.oswego.cs.dl.util.concurrent
Class TimeDaemon

java.lang.Object
  |
  +--edu.oswego.cs.dl.util.concurrent.ThreadFactoryUser
        |
        +--edu.oswego.cs.dl.util.concurrent.TimeDaemon

public class TimeDaemon
extends ThreadFactoryUser

A general-purpose timer daemon, vaguely similar in functionality common system-level utilities like at (and the associated crond) in Unix. Objects of this class maintain a single thread and a task queue that may be used to execute Runnable commands in any of three modes -- absolute (run at a given time), relative (run after a given delay), and periodic (cyclically run with a given delay).

All commands are executed by the single background thread. The thread is not actually started until the first request is encountered. Also, if the thread is stopped for any reason, one is started upon the next request.

If you would instead like commands run in their own threads, you can use as arguments Runnable commands that start their own threads (or perhaps wrap within ThreadedExecutors).

You can also use multiple daemon objects, each using a different background thread. However, one of the reasons for using a time daemon is to pool together processing of infrequent tasks using a single background thread.

Background threads are created using a ThreadFactory. The default factory does not automatically setDaemon status.

[ Introduction to this package. ]


Constructor Summary
TimeDaemon()
          Create a new TimeDaemon
 
Method Summary
static void cancel(Object taskID)
          Cancel a scheduled task.
 Object executeAfterDelay(long millisecondsToDelay, Runnable command)
          Excecute the given command after waiting for the given delay.
 Object executeAt(Date date, Runnable command)
          Execute the given command at the given time.
 Object executePeriodically(long period, Runnable command, boolean startNow)
          Execute the given command every period milliseconds.
 Thread getThread()
          Return the thread being used to process commands, or null if there is no such thread.
 void shutDown()
          Cancel all tasks and interrupt the background thread executing the current task, if any.
 
Methods inherited from class edu.oswego.cs.dl.util.concurrent.ThreadFactoryUser
getThreadFactory, setThreadFactory
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

TimeDaemon

public TimeDaemon()
Create a new TimeDaemon
Method Detail

cancel

public static void cancel(Object taskID)
Cancel a scheduled task. The task will be cancelled upon the next opportunity to run it. This has no effect if this is a one-shot task that has already executed. If an execution is in progress, it will complete normally, but if it is a periodic task, future iterations are cancelled.
Parameters:
taskID - -- a task reference returned by one of the execute commands
Throws:
ClassCastException - if the taskID argument is not of the type returned by an execute command.

executeAfterDelay

public Object executeAfterDelay(long millisecondsToDelay,
                                Runnable command)
Excecute the given command after waiting for the given delay.
Parameters:
millisecondsToDelay - -- the number of milliseconds from now to run the command.
command - -- the command to run after the delay.
Returns:
taskID -- an opaque reference that can be used to cancel execution request

Sample Usage. You can use a TimeDaemon to arrange timeout callbacks to break out of stuck IO. For example (code sketch):

 class X {   ...
 
   TimeDaemon timer = ...
   Thread readerThread;
   FileInputStream datafile;
 
   void startReadThread() {
     datafile = new FileInputStream("data", ...);
 
     readerThread = new Thread(new Runnable() {
      public void run() {
        for(;;) {
          // try to gracefully exit before blocking
         if (Thread.currentThread().isInterrupted()) {
           quietlyWrapUpAndReturn();
         }
         else {
           try {
             int c = datafile.read();
             if (c == -1) break;
             else process(c);
           }
           catch (IOException ex) {
            cleanup();
            return;
          }
       }
     } };

    readerThread.start();

    // establish callback to cancel after 60 seconds
    timer.executeAfterDelay(60000, new Runnable() {
      readerThread.interrupt();    // try to interrupt thread
      datafile.close(); // force thread to lose its input file 
    });
   } 
 }
 

executeAt

public Object executeAt(Date date,
                        Runnable command)
Execute the given command at the given time.
Parameters:
date - -- the absolute time to run the command, expressed as a java.util.Date.
command - -- the command to run at the given time.
Returns:
taskID -- an opaque reference that can be used to cancel execution request

executePeriodically

public Object executePeriodically(long period,
                                  Runnable command,
                                  boolean startNow)
Execute the given command every period milliseconds. If startNow is true, execution begins immediately, otherwise, it begins after the first period delay.
Parameters:
period - -- the period, in milliseconds. Periods are measured from start-of-task to the next start-of-task. It is generally a bad idea to use a period that is shorter than the expected task duration.
command - -- the command to run at each cycle
startNow - -- true if the cycle should start with execution of the task now. Otherwise, the cycle starts with a delay of period milliseconds.
Returns:
taskID -- an opaque reference that can be used to cancel execution request
Throws:
IllegalArgumentException - if period less than or equal to zero.

getThread

public Thread getThread()
Return the thread being used to process commands, or null if there is no such thread. You can use this to invoke any special methods on the thread, for example, to interrupt it.

shutDown

public void shutDown()
Cancel all tasks and interrupt the background thread executing the current task, if any. (A new background thread will be started if new execution requests are encountered.)

Colt 1.0.2

Submit a bug or feature. Check the Colt home page for the latest news.