Non blocking event scheduling in python

允我心安 提交于 2019-12-22 06:22:52

问题


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


来源:https://stackoverflow.com/questions/27190809/non-blocking-event-scheduling-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!