Timer vs. ScheduledExecutorService scheduling - java

One of the recommended uses of the ScheduledExecutorService is as a direct replacement for the Timer class, as discussed in numerous StackOverflow topics already:
Java Timer vs ExecutorService?
Difference between TimerTask and Executors.newScheduledThreadPool(1)
What is the difference between schedule and scheduleAtFixedRate?
Android Timer schedule vs scheduleAtFixedRate
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?

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleAtFixedRate(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 ;-)

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.

Related

Does Java Timer create a new thread?

I created a Timer object scheduled to run every 1 second and the run method takes 20 seconds to complete. The
Timer.schedule method works as expected: it starts the task immediately after the first task is completed in 20 seconds.
But the Timer.scheduleAtFixedRate method also behaves in the same way. This is what is in the documentation:
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up.".
I expect that multiple threads will be spun to catch up, but this is not happening.
How can this be explained? What is a good example to demonstrate the difference between these methods?
Java documentation for the Timer class:
Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. Timer tasks should complete quickly. If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks, which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes.
The expectation that additional threads will be created to catch up is incorrect. According to the documentation, Timer tasks should complete quickly. A Timer task should not take 20 seconds to complete. An alternative is the ScheduledThreadPoolExecutor class:
A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required.
To answer the second question: The difference is that the schedule method "schedules the specified task for repeated fixed-delay execution" and the
scheduleAtFixedRate method "schedules the specified task for repeated fixed-rate execution". This answer explains this difference well.
yes,Java Timer object can be created to run the associated tasks as a daemon thread.
https://www.geeksforgeeks.org/java-util-timer-class-java/

Run task periodically in Java using java.util.TimerTask

While scheduling tasks using java.util.TimerTask how i can make sure that run method will execute only after current execution is completed, otherwise tasks queue size will keep growing and eventually task will be executing always. i am beginner and looking help
Use ExecutorService#scheduleWithFixedDelay(). This will start the 'delay' when the current task finishes (as opposed to scheduleAtFixedRate())
Use a java.util.Timer with the TimerTask. One of these timer's two methods can be used:
schedule(TimerTask task, long delay, long period)
scheduleAtFixedRate(TimerTask task, long delay, long period)
Where:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Also, refer this article: What is the difference between schedule and scheduleAtFixedRate?

Difference between scheduleAtFixedRate() and schedule() in Java

Can anybody explain me What is difference between scheduleAtFixedRate() and schedule() methods in Timer Class with simple code example.
The schedule(TimerTask task,long delay,long period) method is used to schedule the specified task for repeated fixed-delay execution, beginning after the specified delay.
The scheduleAtFixedRate(TimerTask task,long delay,long period) method is used to schedule the specified task for repeated fixed-rate execution, beginning after the specified delay

TimerTask vs Thread.sleep vs Handler postDelayed - most accurate to call function every N milliseconds?

What is the most accurate way to call a function every N milliseconds?
Thread with Thread.sleep
TimerTask
Handler with postDelayed
I modified this example using Thread.sleep and it's not very accurate.
I'm developing a music app that will play sounds at a given BPM. I understand it's impossible to create an entirely accurate metronome and I don't need to - just looking to find the best way to do this.
Thanks
There are some disadvantages of using Timer
It creates only single thread to execute the tasks and if a task
takes too long to run, other tasks suffer.
It does not handle
exceptions thrown by tasks and thread just terminates, which affects
other scheduled tasks and they are never run
ScheduledThreadPoolExecutor deals properly with all these issues and it does not make sense to use Timer.. There are two methods which could be of use in your case.. scheduleAtFixedRate(...) and scheduleWithFixedDelay(..)
class MyTask implements Runnable {
#Override
public void run() {
System.out.println("Hello world");
}
}
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
long period = 100; // the period between successive executions
exec.scheduleAtFixedRate(new MyTask(), 0, period, TimeUnit.MICROSECONDS);
long delay = 100; //the delay between the termination of one execution and the commencement of the next
exec.scheduleWithFixedDelay(new MyTask(), 0, delay, TimeUnit.MICROSECONDS);
On Android you can create Thread with it's own Handler/Message Queue. It's quite accurate. When you see Handler documentation you can see, that it was designed for that.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
They are all the same precision-wise. Java timing precision is subject to the precision and accuracy of system timers and schedulers and is not guaranteed. See Thread.sleep and Object.wait API.
Using TimerTask for the loop action is the better one. Recommend

What happens if a TimerTask takes longer to execute than the specified interval?

When using
Timer.schedule(TimerTask task, long delay, long period)
(i.e. with fixed-delay execution), what happens if the specified TimerTask's run() method takes longer than period to complete? Is it possible that two concurrent TimerTask threads will be running because of this?
And if so, is there a way to avoid it?
Timer's documentation says the following:
Timer tasks should complete quickly. If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks, which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes.
That is, concurrent TimerTask threads will not be running. The tasks will accumulate into a queue. This may or may not be appropriate (more likely, not).
Timer and TimerTask don't handle this sort of situation well. If you want to handle it better, then don't use those classes.
java.util.concurrent.ScheduledExecutorService provides two scheduling methods, scheduleAtFixedRate and scheduledWithFixedDelay, which govern what happens when tasks "bunch up".
scheduleAtFixedRate:
Creates and executes a periodic action
that becomes enabled first after the
given initial delay, and subsequently
with the given period; that is
executions will commence after
initialDelay then initialDelay+period,
then initialDelay + 2 * period, and so
on. If any execution of the task
encounters an exception, subsequent
executions are suppressed. Otherwise,
the task will only terminate via
cancellation or termination of the
executor. If any execution of this
task takes longer than its period,
then subsequent executions may start
late, but will not concurrently
execute.
scheduleWithFixedDelay:
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. If any
execution of the task encounters an
exception, subsequent executions are
suppressed. Otherwise, the task will
only terminate via cancellation or
termination of the executor.
You can create ScheduledExecutorService instances using the Executors factory class.

Categories

Resources