Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non blocking event scheduling in python

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?

like image 475
Sreejith Alappuzha Avatar asked Nov 28 '14 14:11

Sreejith Alappuzha


Video Answer


1 Answers

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() 
like image 119
unutbu Avatar answered Sep 28 '22 15:09

unutbu