Non blocking event scheduling in python

2019-05-10 03:22发布

问题:

Is it possible to schedule a function to execute at every xx millisecs in python,without blocking other events/without using delays/without using sleep ?

What is the best way to repeatedly execute a function every x seconds in Python? explains how to do it with sched module, but the solution will block the entire code execution for the wait time(like sleep).

The simple scheduling like the one given below is non blocking, but the scheduling works only once- rescheduling is not possible.

from threading import Timer
def hello():
    print "hello, world" 

t = threading.Timer(10.0, hello)
t.start() 

I am running the python code in Raspberry pi installed with Raspbian.Is there any way to either schedule the function in non blocking way or trigger it using 'some features' of the os?

回答1:

You can "reschedule" the event by starting another Timer inside the callback function:

import threading

def hello():
    t = threading.Timer(10.0, hello)
    t.start()
    print "hello, world" 

t = threading.Timer(10.0, hello)
t.start()