繁体   English   中英

如何每 0.2 秒运行一次函数中的一段代码,持续 5 秒?

[英]How to run a piece of code in a function every 0.2 seconds for 5 seconds?

这是我想调用的函数:

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,并且不会停止。 这只是我想运行的一个测试函数,以查看该函数是否按预期运行。

你可以试试“for”和“sleep”

i=0
for (i<=25)
   printit()
   time.sleep(0.2)
   i=i+1

这是为了在 5 秒内调用 printit 函数 25 次

如果您的任务是在一定程度上延迟生成线程的确切次数,我看不出有任何理由使用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)
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 秒并停止循环

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM