非轮询/非阻塞定时器?

tar*_*yte 11 python timer

到目前为止,我发现的最佳解决方案是使用该sleep()功能.我想在计时器到期事件发生时运行我自己的回调函数.是否有任何事件驱动的方式去做?

from time import sleep

# Sleep for a minute
time.sleep(60)
Run Code Online (Sandbox Code Playgroud)

Bac*_*ach 14

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

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...)
Run Code Online (Sandbox Code Playgroud)

你也可以将args和kwargs传递给你的回调.看到这里.

  • 您不能/不需要重置计时器.它只工作一次. (4认同)
  • 不过,我似乎无法重置计时器。我不希望这个继续运行。我想在另一个事件上启动它,然后获取到期事件。当我尝试timer.cancel()时,我得到:raise RuntimeError(“线程只能启动一次”)RuntimeError:线程只能启动一次 (2认同)

Jav*_*ier 8

我认为这可能非常简单.看看这个例子.它甚至可以在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()
Run Code Online (Sandbox Code Playgroud)

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

编辑

另一个很好的例子,考虑到@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?
Run Code Online (Sandbox Code Playgroud)


Aar*_*all 7

有时一个简单的解决方案是最好的,即使它轮询时间。我之前已经使用它取得了巨大的成功 - 如果您的线程没有停止,它不会阻塞。

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

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

和用法:

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

>>> event_minute_later(event)
1393962526.73
False
>>> event_minute_later(event)
1393962562.9
True
Run Code Online (Sandbox Code Playgroud)