Java Android计时器计划与scheduleAtFixedRate

Java Android计时器计划与scheduleAtFixedRate,java,android,multithreading,timer,scheduled-tasks,Java,Android,Multithreading,Timer,Scheduled Tasks,我正在编写一个Android应用程序,每10分钟录制一次音频。我用定时器来做这件事。但是scheduleAtFixedRate和scheduleAtFixedRate之间有什么区别呢?使用一种方法比使用另一种方法有性能优势吗?一个简单的schedule()方法将立即执行,scheduleAtFixedRate()方法将使用额外的参数,用于在特定的时间间隔内重复任务 通过查看语法: Timer timer = new Timer(); timer.schedule( new performCla

我正在编写一个Android应用程序,每10分钟录制一次音频。我用定时器来做这件事。但是scheduleAtFixedRate和scheduleAtFixedRate之间有什么区别呢?使用一种方法比使用另一种方法有性能优势吗?

一个简单的
schedule()
方法将立即执行,
scheduleAtFixedRate()
方法将使用额外的参数,用于在特定的时间间隔内重复任务

通过查看语法:

Timer timer = new Timer(); 
timer.schedule( new performClass(), 30000 );
这将在30秒时间间隔结束后执行一次。一种时间行动

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 );

这将在1秒后开始,每隔30秒重复一次。

如果是计划,它只在适当的时间到来时执行一次。另一方面,scheduleAtFixedRate有一个额外的参数period,它包含后续执行之间的时间量(以毫秒为单位)

更多信息可以在这里找到


,long)

最好用以下方法来解释这种差异:

固定速率计时器(
scheduleAtFixedRate()
)基于开始时间(因此每次迭代将在
startTime+iterationNumber*delayTime
执行)

在固定速率执行中,每个执行都是相对于初始执行的计划执行时间进行计划的。如果执行因任何原因(如垃圾收集或其他后台活动)而延迟,则两个或多个执行将快速连续发生以“赶上”

固定延迟计时器(
schedule()
)基于上一次执行(因此每次迭代将在
lastExecutionTime+delayTime
)执行)

在固定延迟执行中,每次执行都是相对于前一次执行的实际执行时间进行调度的。如果执行因任何原因(如垃圾收集或其他后台活动)而延迟,则后续执行也将延迟

除此之外,没有区别。您也不会发现显著的性能差异


如果在希望与其他内容保持同步的情况下使用此选项,则需要使用
scheduleAtFixedRate()
schedule()
的延迟可能会漂移并引入错误。

根据java.util.Timer.TimerImpl.TimerHeap代码

// 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;
}
--

将设置
task.fixedRate=false

java.util.Timer.scheduleAtFixedRate(TimerTask task, long delay, long period)
将设置
task.fixedRate=true

顺便说一句,当屏幕关闭时,计时器不工作。 您应该使用AlarmManager


有一个示例:

实际上,如果您指定第三个参数,
schedule()
也将重复。当我发表评论时,您没有这样做!评论被撤销不,我是在您注释它之前做的,然后我在代码中注释了该部分,并编写了另一个方法scheduleAtFixRate();这两个电话是一样的吗?timer.schedule(新的performClass(),0,30000);和timer.scheduleAtFixedRate(新的performClass(),0,30000);为什么并没有控制的时间必须大于延迟。例如,它意味着什么。(周期小于延迟)
schedule()
也可以指定
period
参数。请注意,当您将系统时间更改为过去的某个时间(在android上,这需要根用户)时,计时器在上述两种情况下都不会在该时间段内执行任务。答案中对此进行了很好的解释。
java.util.Timer.scheduleAtFixedRate(TimerTask task, long delay, long period)