计时器中断线程python [英] timer interrupt thread python

查看:198
本文介绍了计时器中断线程python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在python中创建一个精确的计时器,或者像OS所允许的那样精确.但是它似乎比我最初想象的要复杂.

I've been trying to make a precise timer in python, or as precise a OS allows it to be. But It seams to be more complicated than I initially thought.

这就是我想要的工作方式:

This is how I would like it to work:

from time import sleep
from threading import Timer

def do_this():
    print ("hello, world")


t = Timer(4, do_this)
t.start()
sleep(20)
t.cancel()

在20秒内,我将每四秒钟执行一次'do_this'.但是,"do_this"执行一次,然后脚本会在20秒后终止.

Where during 20 seconds I would execute 'do_this' every fourth second. However 'do_this' executes once then the script terminates after 20 seconds.

另一种方法是使用while循环创建一个thred.

Another way would be to create a thred with a while loop.

import time
import threading
import datetime

shutdown_event = threading.Event()

def dowork():
    while not shutdown_event.is_set():
        print(datetime.datetime.now())
        time.sleep(1.0)

def main():

    t = threading.Thread(target=dowork, args=(), name='worker')
    t.start()

    print("Instance started")

    try:
        while t.isAlive():
            t.join(timeout=1.0)
    except (KeyboardInterrupt, SystemExit):
            shutdown_event.set()
    pass

if __name__ == '__main__':
    main()

该线程按预期执行,但出现时间偏移.在这种情况下,我必须通过相应地调整睡眠来补偿在while循环中执行代码所需的时间.

This thread executes as expected but I get a timing drift. I in this case have to compensate for the time it takes to execute the code in the while loop by adjusting the sleep accordingly.

在python中是否有一种简单的方法可以每秒(或任何间隔)执行一个计时器,而不引入与系统时间相比的偏移,而不必补偿sleep(n)参数?

Is there a simple way in python to execute a timer every second (or any interval) without introducing a drift compared to the system time without having to compensate the sleep(n) parameter?

感谢您的帮助,

/安德斯

推荐答案

如果dowork()的运行时间始终少于间隔时间,则可以每4秒循环生成一个新线程:

If dowork() always runs in less time than your intervals, you can spawn a new thread every 4 seconds in a loop:

def dowork():
  wlen = random.random()
  sleep(wlen) # Emulate doing some work
  print 'work done in %0.2f seconds' % wlen

def main():
  while 1:
    t = threading.Thread(target=dowork)
    time.sleep(4)

如果dowork()可能会运行4秒钟以上,那么在主循环中,您要确保在生成新任务之前已完成上一个任务.

If dowork() could potentially run for more than 4 seconds, then in your main loop you want to make sure the previous job is finished before spawning a new one.

但是,time.sleep()本身可以漂移,因为无法保证线程实际上将挂起多长时间. 正确的处理方式是弄清楚该工作在剩余时间间隔内花费了多少时间和睡眠时间.我认为这是UI和游戏渲染引擎的工作方式,它们必须在固定时间每秒显示固定数量的帧,并且渲染每个帧可能需要不同的时间长度才能完成.

However, time.sleep() can itself drift because no guarantees are made on how long the thread will actually be suspended. The correct way of doing it would be to figure out how long the job took and sleep for the remaining of the interval. I think this is how UI and game rendering engines work, where they have to display fixed number of frames per second at fixed times and rendering each frame could take different length of time to complete.

这篇关于计时器中断线程python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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