[英]Pythonmodule to make a loop run exactly every n seconds
我正在尋找一個pythonmodule,它提供了一個對象,該對象具有自上次睡眠以來可以睡眠n秒鍾的方法。 我認為這個例子可以解釋:
import time
def skipped(n):
print("Ohhh no, skipped {0} ticks!".format(n))
# the object of the module im searching for
timer = Timer()
# mainloop
while True:
# a short calculation wouldn't cause skipped() to be called
time.sleep(0.1)
# but a too long calculation would
# theoretically this should cause "Ohhh no, skipped 0.5 ticks!" to be printed
#time.sleep(3)
# wait until n seconds since the last sleep passed
# if already more than n seconds passed call skipfunc((secondspassed-n)/n)
timer.sleep(n=2, skipfunc=skipped)
但這只是一個例子,對象並不能完全像這樣工作。 例如,如果跳過跳動,該方法將引發異常,那也是可以的。
線程模塊提供了它。
import threading
def periodic_call():
threading.Timer(0.1, periodic_call).start()
print('from peridic_call')
periodic_call()
由於有許多不同的變體可以處理此問題,並且執行此操作的代碼非常簡單,因此沒有用於此的顯式模塊:
interval = 2
while True:
next_run = time.time() + interval
do_something()
delta = next_run - time.time()
if delta < 0:
skipped(delta/-interval)
else:
time.sleep(delta)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.