Home > Mobile >  How to run a piece of code in a function every 0.2 seconds for 5 seconds?
How to run a piece of code in a function every 0.2 seconds for 5 seconds?

Time:03-28

This it the function I want to call:

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)

Every time server_fn() is called, I want it to run that code 25 times in 5 seconds. How should I do that?

I tried this:

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()

but the output just displays 1 every line forever, and doesn't stop. This was just a test function I wanted to run to see if the function is running as I expected it to.

CodePudding user response:

You can try "for" and "sleep"

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

This is for calling printit function 25 times in 5 seconds

CodePudding user response:

I don't see any reason to use Timer if your task is to spawn a thread exact amount of times with some delay. It could be done with simple for loop and 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

Here is a simple example of app which spawn a thread every 200 milliseconds:

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)

You can help my country, check my profile info.

CodePudding user response:

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 would increase by 1 every 0.2 seconds until it reaches 25 which will make it exactly 5 seconds and stop the Loop

  • Related