這是我要呼叫的函式:
def server_fn():
#the code below this line is the code I wanna run every 0.2s and stop after a total of 5s
frame = url_to_image('http://192.168.180.161/1600x1200.jpg')
ans = get_model_output(frame)
if ans == 1 :
url = 'http://192.168.180.161/post/1'
else:
url = 'http://192.168.180.161/post/0'
response = requests.get(url)
print(response.content)
每次server_fn()呼叫時,我希望它在 5 秒內運行該代碼 25 次。我該怎么做?
我試過這個:
import threading
def printit():
thread = threading.Timer(1.0, printit)
thread.start()
x = 0
if x == 10:
thread.cancel()
else:
x = 1
print(x)
printit()
但輸出永遠只顯示 1 每行,并且不會停止。這只是我想運行的一個測驗函式,以查看該函式是否按我的預期運行。
uj5u.com熱心網友回復:
你可以試試“for”和“sleep”
i=0
for (i<=25)
printit()
time.sleep(0.2)
i=i 1
這是為了在 5 秒內呼叫 printit 函式 25 次
uj5u.com熱心網友回復:
Timer如果您的任務是在一些延遲的情況下生成一個執行緒的確切次數,我認為沒有任何理由使用。可以通過簡單的for回圈和time.sleep().
from threading import Thread
from time import sleep
...
for i in range(25):
Thread(target=printit).start() # spawn a thread
sleep(0.2) # delay
這是一個簡單的應用程式示例,它每 200 毫秒生成一個執行緒:
from threading import Thread, Lock
from time import time, sleep
from random import random
print_lock = Lock()
def safe_print(*args, **kwargs):
print_lock.acquire()
print(*args, **kwargs)
print_lock.release()
def func(id_):
sleep_time = random()
safe_print(time(), id_, "- enter, sleep_time", sleep_time)
sleep(sleep_time)
safe_print(time(), id_, "- leave")
for i in range(25):
safe_print(time(), "starting new thread with id", i)
Thread(target=func, args=(i,)).start()
sleep(0.2)
你可以幫助我的國家,查看我的個人資料資訊。
uj5u.com熱心網友回復:
from time import sleep
i = 0
while i!=25:
"Your Code"
sleep(0.2) #repeats the code after every 0.2 seconds delay 25 times (25*0.2 = 5 seconds)
i = i 1
i將每 0.2 秒增加 1,直到達到 25,這將使其正好 5 秒并停止回圈
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/450255.html
上一篇:同步塊中的反射類
