-1

I need to start the execution of a function foo() every 10 seconds, and the foo() function takes a random time between 1 and 3 seconds to be executed.

import time
import datetime

def foo():
    # ... code which takes a random time between 1 and 3 seconds to be executed

while True:
    foo()
    time.sleep(10)

of course in the above example the function foo() is not executed every 10 seconds but every 10 + random seconds.

Is there a way to start executing foo() each exactly 10 seconds? I'm sure it's something related with threading but can't find a proper example.

user1403546
  • 1,680
  • 4
  • 22
  • 43

3 Answers3

3

Yes, it is related to threading as you want to spawn a different thread to execute your function asynchronously - the parent process will wait 10 seconds irrespective of how long the thread takes to execute.

This is a standard way to do this in python:

import threading

def print_some():
  threading.Timer(10.0, print_some).start()
  print "Hello!"

print_some()

See more here: http://www.bogotobogo.com/python/Multithread/python_multithreading_subclassing_Timer_Object.php

So in your case it would be:

import threading
import time

def foo():
    threading.Timer(10.0, foo).start()
    print("hello")

if __name__ == '__main__':
    foo()
Mindaugas Bernatavičius
  • 3,757
  • 4
  • 31
  • 58
1

If you want threading here you go!

import threading

def foo():
   # does stuff

while True:
   t = threading.Thread(target=foo)
   t.start()
   time.sleep(10)
Stefan Collier
  • 4,314
  • 2
  • 23
  • 33
0

Sample code.

import time
import datetime

def foo():
    # ... code which takes a random time between 1 and 3 seconds to be executed

while True:
    start = time.time() 
    foo(random number)
    end = time.time()  - start
    time.sleep(10 - end)
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49