[Issue]
Why is the task(TimerTask) triggered many times before late resume?
[Sample code]
private Timer timer;
private BISTTimerTask bistTimerTask;
timer = new Timer();
bistTimerTask = new BISTTimerTask();
timer.scheduleAtFixedRate(bistTimerTask, 0, 1000);
[Source code]
Java.util.timer.java
private void mainLoop() {
while (true) {
try {
TimerTask task;
boolean taskFired;
synchronized(queue) {
//……………………
// Queue nonempty; look at first evt and do the right thing
long currentTime, executionTime;
task = queue.getMin();
synchronized(task.lock) {
//………………………….
currentTime = System.currentTimeMillis();
executionTime = task.nextExecutionTime;
if (taskFired = (executionTime<=currentTime)){
//……………………………..
queue.rescheduleMin(
executionTime+ task.period);
}
}
if (!taskFired) // Task hasn't yet fired; wait
queue.wait(executionTime - currentTime);
}
if (taskFired) // Task fired;run it, holding no locks
task.run();
} catch(InterruptedException e) {
}
}
}
|
|
|
|
|
Before suspend |
currentTime + task.period = executionTime
|
The timer task needs to wait a period(1s). |
|
After resume |
The value of the variable(currentTime) is changed, but the variable(executionTime) still keeps the value before suspend. Here’s the equation between both variables. executionTime + suspend time = currentTime
|
It’ll trigger timer task without waiting many times.
|
[log Analysis]
logs_1012_1828\6.20161012_094834
|
|
|
|
kernel_20161012_094834-1.log
|
<6>[ 306.308898] Suspended for 83.258 seconds <6>[ 307.029785] suspend: exit suspend, ret = 0 (2016-10-12 09:54:48.738128655 UTC)
|
|
main_20161012_094834-1.log
|
We can only check the string highlighted in the code below. The string had appeared 84 times near that time in main log, so It also means that the timer task was triggered 84 times. private class BISTTimerTask extends TimerTask { public void run() { //…………………………. new_tic = System.currentTimeMillis(); if(new_tic-last_tic<100){ Log.d("feong", "resume"); last_tic = new_tic; return; } last_tic = new_tic; //………………………………. } Please check the file(timer_trigger.txt).
|
|
|
|
定时任务重复触发原因
本文探讨了Java中使用TimerTask时出现的任务重复触发问题。通过分析源码,解释了在设备挂起后再恢复运行时,任务为何会连续多次触发而非等待设定的周期。
4365

被折叠的 条评论
为什么被折叠?



