I'm writing an Android application that records audio every 10 minutes. I am using a Timer to do that. But what is the difference between schedule and scheduleAtFixedRate? Is there any performance benefit in using one over the other?
Try this: Timer waitTimer; void exampleMethod() { if (waitTimer == null ) { //initialize your Timer here ... }
A task that can be scheduled for one-time or repeated execution by a Timer . A timer task is not reusable. Once a task has been scheduled for execution on a Timer or cancelled, subsequent attempts to schedule it for execution will throw IllegalStateException .
Timer provides method to schedule Task where the task is an instance of TimerTask class, which implements the Runnable interface and overrides run() method to define task which is called on scheduled time.
A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.
The difference is best explained by this non-Android documentation:
Fixed-rate timers (scheduleAtFixedRate()
) are based on the starting time (so each iteration will execute at startTime + iterationNumber * delayTime
).
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."
Fixed-delay timers (schedule()
) are based on the previous execution (so each iteration will execute at lastExecutionTime + delayTime
).
In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well.
Aside from this, there is no difference. You will not find a significance performance difference, either.
If you are using this in a case where you want to stay synchronized with something else, you'll want to use scheduleAtFixedRate()
. The delay from schedule()
can drift and introduce error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With