Accessing running task scheduled with java.util.Timer

Posted by jbatista on Stack Overflow See other posts from Stack Overflow or by jbatista
Published on 2010-05-04T08:45:25Z Indexed on 2010/05/04 8:48 UTC
Read the original article Hit count: 295

Filed under:
|
|

I'm working on a Java project where I have created a class that looks like this (abridged version):

public class Daemon {
  private static Timer[] timerarray=null;
  private static Daemon instance=null;

  protected Daemon() {
    ArrayList<Timer> timers = new ArrayList<Timer>();
    Timer t = new Timer("My application");
    t.schedule(new Worker(), 10000,30000);
    timers.add(t);
    //...
    timerarray = timers.toArray(new Timer[]{});
  }
  public static Daemon getInstance() { 
    if(instance==null) instance=new Daemon(); 
    return instance;
  }
  public SomeClass getSomeValueFromWorker() {

    return theValue;
  }

  /////////////////////////////////////////////
  private class Worker extends TimerTask {
    public Worker() {}
    public void run() {
      // do some work
    }
    public SomeReturnClass someMethod(SomeType someParameter) {
      //
      return something;
    }
  }
  /////////////////////////////////////////////
}

I start this class, e.g. by invoking daemon.getInstance();.

However, I'd like to have some way to access the running task objects' methods (for example, for monitoring the objects' state). The Java class java.util.Timer does not seem to provide the means to access the running object, it just schedules the object instance extending TimerTask.

Are there ways to access the "running" object instanciated within a Timer? Do I have to subclass the Timer class with the appropriate methods to somehow access the instance (this "feels" strange, somehow)? I suppose someone might have done this before ... where can I find examples of this "procedure"?

Thank you in advance for your feedback.

© Stack Overflow or respective owner

Related posts about java

Related posts about timer