在指定的时间间隔前快速触发“计时器" [英] Swift `Timer` firing before the specified time interval

查看:100
本文介绍了在指定的时间间隔前快速触发“计时器"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果执行所花费的时间比指定的 withTimeInterval:更长的时间,我会怀疑 Timer.scheduledTimer()如何触发代码块.

I got a doubt about how Timer.scheduledTimer() fires the block of code if the execution takes more time than the specified withTimeInterval:.

执行该块后还是执行该块的第一条语句时,是否开始倒计时?

Does the countdown to firing starts after the execution of the block or when the first statement of the block is executed?

所以我用以下代码进行了测试:

//Logic is to waste the time in the block which will take more than 5 secs to run.
Timer.scheduledTimer(withTimeInterval: 5, repeats: true){
    timer in
    var sum = 0
    var count = 0

    print("START===================================")
    print(Int64(Date().timeIntervalSince1970 * 1000))
    for i in 2..<100000
    {
        for j in 2..<10000
        {
            sum = i+j
        }
    }

    print(sum) // Ignore this. sum is used here so that compiler might won't be able to remove the loop in the optimisations due to unused variable reason.
    print(Int64(Date().timeIntervalSince1970 * 1000))
    print("END===================================")
}

RunLoop.main.run()

输出:

START===================================
1507965166992
109998
1507965173888
END===================================
START===================================
1507965176993
109998
1507965183890
END===================================
START===================================
1507965186989

当我减去上一个循环的结束时间和当前循环的开始时间时,我总是得到3秒左右的时间.但是我指定了5秒.为什么会这样?

When I subtracted end-time of previous loop and start-time of current loop, I always get around 3 secs. But I have specified 5 secs. Why is that?

推荐答案

检查 计时器 .

概述

...

...

计时器不是实时机制.如果发生计时器的触发时间在长时间运行的循环调用期间或运行循环处于以下模式时:没有监视计时器,直到下一次计时器才会启动运行循环检查计时器.因此,实际时间定时器触发可能要晚得多.

A timer is not a real-time mechanism. If a timer’s firing time occurs during a long run loop callout or while the run loop is in a mode that isn't monitoring the timer, the timer doesn't fire until the next time the run loop checks the timer. Therefore, the actual time at which a timer fires can be significantly later.

...

因此,计时器不会总是在准确的时间执行您的代码块.它将其安排在运行循环中.如果有一些重要的线程要执行,那么您的代码将被延迟.因此,要维持固定的触发时间,请查看指定 tolerance

So, the timer doesn't execute your block of code at the exact time always. It schedules it on the run loop. If there are some important threads to execute, then your code will be delayed. So, to maintain a fixed firing time, look at specifying tolerance value.

比较重复计时器和不重复计时器

您指定计时器在创建时是重复还是不重复时间.非重复计时器触发一次,然后使其自身无效自动,从而防止计时器再次触发.经过相比之下,重复计时器触发,然后在相同的运行循环.重复计时器始终根据以下时间安排自己的时间:计划的点火时间,而不是实际的点火时间.为了例如,如果计划将计时器在特定时间触发,并且此后每5秒钟,计划的发射时间将始终下降以原始的5秒时间间隔为准,即使实际触发时间被延迟了.如果点火时间延迟到可以通过一个或多个预定的触发时间,仅触发计时器在该时间段内一次;之后,计时器将重新安排点火,以备将来的下一个预定点火时间.

You specify whether a timer is repeating or nonrepeating at creation time. A nonrepeating timer fires once and then invalidates itself automatically, thereby preventing the timer from firing again. By contrast, a repeating timer fires and then reschedules itself on the same run loop. A repeating timer always schedules itself based on the scheduled firing time, as opposed to the actual firing time. For example, if a timer is scheduled to fire at a particular time and every 5 seconds after that, the scheduled firing time will always fall on the original 5-second time intervals, even if the actual firing time gets delayed. If the firing time is delayed so far that it passes one or more of the scheduled firing times, the timer is fired only once for that time period; the timer is then rescheduled, after firing, for the next scheduled firing time in the future.

在这里,它说倒计时是在第一个计时器启动时开始的,而不是在计时器结束时开始的.

Here, it says that the countdown starts when the first timer is started but not when the timer has ended.

第一个问题:

执行块后是否开始倒计时还是执行该块的第一条语句?

Does the countdown to firing starts after the execution of the block or when the first statement of the block is executed?

答案:两者都不是.倒数计时在第一个计时器启动时开始.

Answer: Neither. The countdown starts when the first timer is started.

第二个问题:

当我减去上一个循环的结束时间和当前的开始时间时循环,我总是在 3 秒左右.但是我指定了5秒.为什么是那?

When I subtracted endtime of previous loop and starttime of current loop, I always get around 3 sec. But I have specified 5 sec. Why is that?

答案:

1).就像我在第一个问题中所说的那样,倒计时是在第一个计时器启动后开始的.

1). As I said in your 1st question, the countdown starts after the first timer has started.

2).他们在比较重复和不重复计时器中说,如果逻辑花费的时间比 timer 中指定的时间长,那么执行完成后仅执行一次代码并在指定的时间之后.

2). In Comparing Repeating and Nonrepeating Timers, they said that if the logic takes more time than the specified time in the timer then it executes the code only once after the completion of the execution block and also after the specified time.

Timer interval: 5

Time for block to complete: 8

Then next code will be executed at: 8 + 2 = 10 secs(as 5 is the interval)

根据您的代码输出:

START===================================
1507965166992                           <---------+
109998                                            |
1507965173888                                     |
END===================================            |
START===================================          |
1507965176993                           <---------+
109998                                            |
1507965183890                                     |
END===================================            |
START===================================          |
1507965186989                           <---------+

检查上方标记箭头的时差.它恰好在10秒后执行代码(与我上面给出的解释相同).

Check the time difference of the marked arrow above. It executes the code exactly after 10secs(which is same as the explanation I have given above).

提示:提问前请务必查看并阅读文档.

Tip: Always look at and read the documentation before asking.

这篇关于在指定的时间间隔前快速触发“计时器"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆