def gobject.timeout_add(interval, callback, ...)这个函数被用于设置一个定时器,以便在固定的时间间隔 interval (单位:毫秒)后调用 callback 函数,之后的参数(...部分)则被传送给 callback 函数。callback 函数需要返回一个 bool 值,如果为 True 的话,则说明该定时器需要继续运行;而如果值为 False 的话,该计时器就会停止工作,不再定时调用 callback 函数。callback 函数执行需要花费一定时间,因此可能会影响到定时器的准确性。按照官方文档给出的信息:
Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to 'catch up' time lost in delays).
假设 callback 函数执行时间为 1 秒,interval 的设置为 3 秒。那么当注册了定时器之后的第 3 秒结束时,也就是第一个 interval 的结尾,callback 函数被调用,在第 4 秒末执行完成,并返回 True。定时器函数获取 True 之后,知道需要继续执行定时调用,这个时候它会重行调整下次的调用时间,将下一次调用 callback 的时间定为 2 秒后。这是因为 callback 已经执行了 1 秒钟时间,而这 1 秒钟是算在 interval 之内的。所以,并不需要担心 callback 本身的执行带来的计时误差。
但是设想这样的一个情况,callback 的执行时间比较的长。比如 interval 设置为 3 秒,但是 callback 的执行时间是 4 秒。于是在第 3 秒的时候,原本该再次执行 callback 函数,可是由于 之前调用的 callback 还没有返回,于是这个执行计划被跳过,正如上面引用文档的结尾括号里的内容:“it does not try to 'catch up' time lost in delays”。
总结一下,以注册 timeout_add 函数的时间为原点,那么 timeout_add 函数总在最近的一个没有被 callback 函数覆盖的 interval 间隔点进行定时调用。

0 comments:
Post a Comment