4

One of the recommended uses of the ScheduledExecutorService is as a direct replacement for the Timer class, as discussed in numerous StackOverflow topics already:

However, the naming conventions of the methods supported by ScheduledExecutorService and Timer, are not identical. For example, whereas they both have a scheduleAtFixedRate() method, the Timer method

  • schedule​(TimerTask task, long delay, long period)

does not have a namesake counterpart.

Is the ScheduledExecutorService method

  • scheduleWithFixedDelay​(Runnable command, long initialDelay, long delay, TimeUnit unit)

the one to use instead?

PNS
  • 19,295
  • 32
  • 96
  • 143
  • Timer is an implement Class. ScheduledExecutorService is an interface without implementation. So we should compare Timer vs ScheduledThreadPoolExecutor which is an implementation class of ScheduledExecutorService interface – HungNM2 May 14 '22 at 01:38

2 Answers2

1

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleWithFixedDelay(java.lang.Runnable,%20long,%20long,%20java.util.concurrent.TimeUnit)

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html#schedule(java.util.TimerTask,%20long,%20long)

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

I would say - Yes ;-)

SensorSmith
  • 1,129
  • 1
  • 12
  • 25
IEE1394
  • 1,181
  • 13
  • 33
  • 1
    Yes, so it seems, but it is not directly mentioned in any comparative discussion I have found, hence the question. Thanks. :-) – PNS Feb 23 '18 at 21:58
1

Timer#schedule(TimerTask, long, long) has no counterpart in ScheduledExecutorService or its implementation ScheduledThreadPoolExecutor. Although this method is documented as

repeated fixed-delay execution,

it bahaves fundamentally different than ScheduledThreadPoolExecutor#scheduleWithFixedDelay(...) and let alone ScheduledThreadPoolExecutor#scheduleAtFixedRate(...). I have explained the difference between all these methods more detailed as part of this answer.

stonar96
  • 1,359
  • 2
  • 11
  • 39