Android Timer schedule vs scheduleAtFixedRate Android Timer schedule vs scheduleAtFixedRate multithreading multithreading

Android Timer schedule vs scheduleAtFixedRate


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.


A simple schedule() method will execute at once while scheduleAtFixedRate() method takes and extra parameter which is for repetition of the task again & again on specific time interval.

by looking at syntax :

Timer timer = new Timer(); timer.schedule( new performClass(), 30000 );

This is going to perform once after the 30 Second Time Period Interval is over. A kind of timeoput-action.

Timer timer = new Timer(); //timer.schedule(task, delay, period)//timer.schedule( new performClass(), 1000, 30000 );// or you can write in another way//timer.scheduleAtFixedRate(task, delay, period);timer.scheduleAtFixedRate( new performClass(), 1000, 30000 );

This is going to start after 1 second and will repeat on every 30 seconds time interval.


According to java.util.Timer.TimerImpl.TimerHeap code

// this is a repeating task,if (task.fixedRate) {    // task is scheduled at fixed rate    task.when = task.when + task.period;} else {    // task is scheduled at fixed delay    task.when = System.currentTimeMillis() + task.period;}

--

java.util.Timer.schedule(TimerTask task, long delay, long period)

will set task.fixedRate = false;

java.util.Timer.scheduleAtFixedRate(TimerTask task, long delay, long period)

will set task.fixedRate = true;

btw Timer doesn't work when screen is off.You should use AlarmManager.

There is sample:http://developer.android.com/training/scheduling/alarms.html