2015-11-02 37 views
1

我是新來的蟒蛇,我想知道,如果有,將在一定的時間間隔重複的事件,有點像如何設置重複的循環在蟒蛇一定的時間間隔?

setInterval() 
在Javascript

的功能。我知道我可以只使用

time.sleep() 

在規則循環內,但我想知道是否有更好的方法來做到這一點。提前致謝。

+3

你會NEAD線程。參見[這個問題](http://stackoverflow.com/questions/2697039/python-equivalent-of-setinterval)(或通過在谷歌搜索等)。 – Delgan

回答

1

下面是@Mathias艾丁格的

由於call_at_interval運行在一個單獨的線程已經簡化版本,沒有必要使用Timer,因爲它會產生一個另外的螺紋。

正好眠,並直接調用回調。

from threading import Thread 
from time import sleep 

def call_at_interval(period, callback, args): 
    while True: 
     sleep(period) 
     callback(*args) 

def setInterval(period, callback, *args): 
    Thread(target=call_at_interval, args=(period, callback, args)).start() 

def hello(word): 
    print("hello", word) 

setInterval(10, hello, 'world!') 
1
from threading import Timer, Thread 

def call_at_interval(time, callback, args): 
    while True: 
     timer = Timer(time, callback, args=args) 
     timer.start() 
     timer.join() 

def setInterval(time, callback, *args): 
    Thread(target=call_at_interval, args=(time, callback, args)).start() 

需要兩個函數避免使setInterval阻塞調用。

您可以使用它像這樣:

def hello(word): 
    print("hello", word) 

setInterval(10, hello, 'world!') 

它將打印'hello world!'每十秒鐘。