开发者

Accessing running task scheduled with java.util.Timer

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(int i) {
    if(timerarray==null || i>=timerarray.length) return null;
    /* 
     * **HOW TO ACCESS THE Worker INSTANCE IN THE Timer ARRAY HERE!? **
     */
    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 t开发者_C百科he 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.


Don't use Timer. The ScheduledExecutorService implementations are much better and provide the functionality you want with some extra work. See 409932 for some reasons why to avoid Timer.


In the Daemon constructor, you can collect the instances of Worker into some kind of collection, and add a getter for that collection. This requires increasing the access level to the inner Worker class, as well as making sure that Worker's methods are thread safe.

Another thing: Why do you create a new Timer per job? if your jobs finish quickly, and you don't have too many of them, consider registering all of them in a single Timer. As an alternative, use ScheduledThreadPoolExecutor, where you have a pool of threads of a size you choose.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜