[英]How can I make this timer run forever?
from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start()
此代碼僅觸發計時器一次。
如何讓計時器永遠運行?
謝謝,
更新
這是對的 :
import time,sys
def hello():
while True:
print "Hello, Word!"
sys.stdout.flush()
time.sleep(2.0)
hello()
和這個:
from threading import Timer
def hello():
print "hello, world"
sys.stdout.flush()
t = Timer(2.0, hello)
t.start()
t = Timer(2.0, hello)
t.start()
一個threading.Timer
一次執行的函數。 如果您願意,該功能可以“永遠運行”,例如:
import time
def hello():
while True:
print "Hello, Word!"
time.sleep(30.0)
使用多個Timer
實例會消耗大量資源而沒有真正的附加值。 如果你想要每30秒重復一次的功能,那么一個簡單的方法就是:
import time
def makerepeater(delay, fun, *a, **k):
def wrapper(*a, **k):
while True:
fun(*a, **k)
time.sleep(delay)
return wrapper
然后安排makerepeater(30, hello)
而不是hello
。
對於更復雜的操作,我建議標准庫模塊附表 。
只需重啟(或重新創建)函數中的計時器:
#!/usr/bin/python
from threading import Timer
def hello():
print "hello, world"
t = Timer(2.0, hello)
t.start()
t = Timer(2.0, hello)
t.start()
來自線程導入計時器取決於你想要運行哪一部分,如果它正在創建一個新線程讓我們說每隔10秒就可以從線程導入計時器執行以下操作
import time
def hello():
print "hello, world"
while True: #Runs the code forever over and over again, called a loop
time.sleep(10)#Make it sleep 10 seconds, as to not create too many threads
t = Timer(30.0, hello)
t.start()
如果你想要永遠運行你好的世界,你可以做到以下幾點:
from threading import Timer
def hello():
while True: # Runs this part forever
print "hello, world"
t = Timer(30.0, hello)
t.start()
在python中搜索循環以獲取有關此內容的更多信息
這是我的問題代碼:
import time
from threading import Timer
class pTimer():
def __init__(self,interval,handlerFunction,*arguments):
self.interval=interval
self.handlerFunction=handlerFunction
self.arguments=arguments
self.running=False
self.timer=Timer(self.interval,self.run,arguments)
def start(self):
self.running=True
self.timer.start()
pass
def stop(self):
self.running=False
pass
def run(self,*arguments):
while self.running:
self.handlerFunction(arguments)
time.sleep(self.interval)
另一個腳本頁面:
def doIt(arguments):
#what do you do
for argument in arguments:
print(argument)
mypTimer=pTimer(2,doIt,"argu 1","argu 2",5)
mypTimer.start()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.