非轮询/非阻塞定时器?

时间:2014-03-04 19:15:42

标签: python timer

到目前为止,我发现的最佳解决方案是使用sleep()函数。我想在计时器到期事件发生时运行我自己的回调函数。是否有任何以事件为导向的方式?

from time import sleep

# Sleep for a minute
time.sleep(60)

3 个答案:

答案 0 :(得分:11)

使用threading模块有一个内置的简单解决方案:

import threading

timer = threading.Timer(60.0, callback)
timer.start()  # after 60 seconds, 'callback' will be called

## (in the meanwhile you can do other stuff...)

您还可以将args和kwargs传递给回调。请参阅here

答案 1 :(得分:7)

我认为这可能非常简单。看看这个例子。它甚至可以在python控制台中运行!

from threading import Thread
from time import sleep

# Function to be called when the timer expires
def myFunction():
    print 'Did anyone call me?'

# Function with the timer
def myTimer(seconds):
    sleep(seconds)
    myFunction()

# Thread that will sleep in background and call your function
# when the timer expires.
myThread = Thread(target=myTimer, args=(4,))
myThread.start()

放置您想要的任何秒数,并继续使用控制台或运行主线程/程序。您会注意到,当计时器结束时,将调用该函数。

修改

另一个很好的例子,考虑到@tarabyte的注释,只能根据某个变量或标志的值调用该函数。我希望这将是@tarabyte正在寻找的答案。

from threading import Thread
from time import sleep

myFlag = False

# Function to be called when the flag turns on
def myFunction():
    print 'Did anyone call me?'

def myTimer():
    global myFlag
    while True:
        if myFlag:
            myFunction()
            myFlag = False
        else:
            sleep(1)

# Thread that will sleep in background and call your function
# when the myFlag turns to be True
myThread = Thread(target=myTimer)
myThread.start()

# Then, you can do whatever you want and later change the value of myFlag.
# Take a look at the output inside ipython when the value of myFlag is changed.


In [35]: myFlag
Out[35]: False

In [36]: myFlag = True

In [37]: Did anyone call me?

答案 2 :(得分:2)

有时一个简单的解决方案是最好的,即使它调查时间。我以前用过这个很棒的成功 - 如果你的线程没有停止它就不会阻止它。

我想我会通过检查时间来最简单地管理这个问题,因为这比制定单独的线程解决方案简单得多,资源更经济:

def event_minute_later(event):
    print(time.time()) # use for testing, comment out or delete for production
    return event + 60 < time.time()

用法:

>>> event = time.time()
>>> print(event)
1393962502.62

>>> event_minute_later(event)
1393962526.73
False
>>> event_minute_later(event)
1393962562.9
True