[英]execute block of code independently in the function in Python2.7
我陷入了獨特的場景。 我有一個函數“hello()”,它應該每 10 秒執行一次。 現在,我有一個要求,即在同一個函數中,一段代碼應該每60 秒運行一次,與 10 秒的執行無關。 實現它的最佳方法是什么。 謝謝。
示例代碼:
import time
def hello():
while True:
print "Hello World"
time.sleep(10)
#Do something after every 60 seconds
#Do something after every 86400 seconds
正如我意識到的,你有 3 個獨立的進程。 一種方法是定義三個獨立的線程,並使每個線程每 X 秒運行一次。 順便說一句,您應該使用較新版本的 Python
from multiprocessing import Pool, current_process
import time
def f(seconds):
while True:
print("%s runs every %d seconnds" % (current_process().name, seconds) )
time.sleep(n)
if __name__ == '__main__':
p = Pool(3)
print([w.name for w in p._pool])
p.map(f, [10, 60, 10])
為什么不通過線程來做? 您可以使用獨立計時器創建 3 個線程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.