有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android计时器时间表与scheduleAtFixedRate

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


共 (3) 个答案

  1. # 1 楼答案

    这种差异最好用this non-Android documentation来解释:

    固定速率计时器(scheduleAtFixedRate())基于开始时间(因此每个迭代将在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."

    固定延迟计时器(schedule())基于之前的执行(因此每个迭代将在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.

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

    如果你在想与其他东西保持同步的情况下使用这个,你会想使用scheduleAtFixedRate()。来自schedule()的延迟可能会漂移并引入误差

  2. # 2 楼答案

    一个简单的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秒重复一次