【问题标题】:How to run a piece of code in a function every 0.2 seconds for 5 seconds?如何每 0.2 秒运行一次函数中的一段代码,持续 5 秒?
【发布时间】:2022-12-24 22:55:28
【问题描述】:

这是我想调用的函数:

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

【问题讨论】:

  • 您正在传递给此计时器的函数中初始化 Timer()。这会导致递归和不受控制的线程垃圾邮件。

标签: python multithreading timer


【解决方案1】:

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

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

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

【讨论】:

    【解决方案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 秒并停止循环

    【讨论】:

      【解决方案3】:

      如果您的任务是生成一个线程的确切次数并有一些延迟,我看不出有任何理由使用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)
      

      【讨论】:

        猜你喜欢
        • 2021-12-18
        • 2015-03-27
        • 2018-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-09
        • 2019-06-14
        相关资源
        最近更新 更多