0

I need to execute a piece of code inside a while True loop every, let's say, 5 seconds. I know the threading.Timer(5, foo).start() will be run every 5 seconds but my foo() function depends on a variable inside my while loop.

The foo is actually run on another thread and I don't want to block the current thread just for timing's sake.

+------------------------while #main-thread---------------------------------
|
+..........foo(val)..........foo(val)...........foo(val)............foo(val)
    -5s-              -5s-               -5s-               -5s- 

Something like this:

def input(self):
      vals = []
      while True:
           # fill the vals
           # run `foo(vals)` every 5 seconds

def foo(vals):
    print vals

Is there any Pythonic way of doing this?

Mikael S.
  • 1,005
  • 3
  • 14
  • 28
  • use time.sleep(5) to stop execution for a 5 sec – Sainath Motlakunta Sep 21 '14 at 09:37
  • Your sample code is probably over simplified. The variable is accessible from the other tread, but it might cause problems if you do so. You have to somehow synchronize the access to a variable which used by both threads. But there is no general rule how to do this, as it depends a lot on what you are actually doing with the variable. – Achim Sep 21 '14 at 16:41

1 Answers1

2

Use the sleep function:

import time
def input(self):
      vals = []
      while True:
           # fill the vals
           foo(vals)
           time.sleep(5)

def foo(vals):
    print vals

Note that the command will run every 5 seconds exactly only if the time needed to run it is itself negligible.

damienfrancois
  • 52,978
  • 9
  • 96
  • 110
  • Thanks but the `foo` is actually run on another thread and I don't want to block the current thread. Do you have any idea? – Mikael S. Sep 21 '14 at 16:19
  • Have one `while True` in each thread? One in the main thread for whatever purpose, and one in the other thread for `foo` and `sleep`. – damienfrancois Sep 21 '14 at 19:49