Search code examples
javamultithreadingjakarta-eetimerrunnable

Schedule regular task without extending TimerTask?


How can I run instances of this class repeatedly in separate threads and given intervals? (As you have noticed I am using Java 2 EE).

public class Gate extends AbsDBObject<Gate> implements Runnable{
  public void Run(){
    //Something
  }
}

I have done this before by Gate class extending the TimerTask class and using Timer:

Timer timer = new Timer();
Gate gates = Gate.fetchOne();
timer.schedule(gate, 0, 1000);

But in this case I can't extend any other class. What should I do?


Solution

  • If you use a ScheduledExecutorService then you just execute Runnable objects, rather than TimerTask objects.

    ScheduledExecutorService executorService = 
        new ScheduledThreadPoolExecutor(corePoolSize);
    Gate gate = Gate.fetchOne();
    executorService.scheduleAtFixedRate(gate, 0, 1, TimeUnit.SECONDS);
    

    That saves the need to extend.