Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Timer schedule vs scheduleAtFixedRate

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?

like image 862
DXM Avatar asked Oct 02 '12 04:10

DXM


People also ask

How to schedule timer in Android?

Try this: Timer waitTimer; void exampleMethod() { if (waitTimer == null ) { //initialize your Timer here ... }

What is TimerTask Android?

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 .

What is the relationship between timer and TimerTask?

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.

What is timer class in Android?

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.


1 Answers

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.

like image 61
Cat Avatar answered Oct 24 '22 02:10

Cat