简体   繁体   中英

Python periodic task inside an infinite loop

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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