Search code examples
pythonscheduled-tasksscheduler

Python understanding the scheduler


I've a python scheduler code to print Hello and World!.

import sched
import time

def x():
    print "Hello"

s = sched.scheduler(time.time, time.sleep)
s.enter(10, 1, x, ())
s.run()
print "World!"

This waits for 10 seconds and outputs:

Hello
World!

I think a scheduler's job is to schedule a task without interrupting the current process. But here it's putting the whole program to sleep and behaves just like the below code:

import time

def x():
    print "Hello"

time.sleep(10)
x()
print "World!"

I guess the scheduler makes the program to sleep due to the time.sleep parameter in sched.scheduler(time.time, time.sleep). Is there anyway we can make it work just like a real-time scheduler without blocking the main process without using any multithreading or multiprocessing?


Solution

  • From the docs:

    In multi-threaded environments, the scheduler class has limitations with respect to thread-safety, inability to insert a new task before the one currently pending in a running scheduler, and holding up the main thread until the event queue is empty. Instead, the preferred approach is to use the threading.Timer class instead.

    from threading import Timer
    
    def x():
        print "Hello"
    
    Timer(10, x, ()).start()
    print "World!"
    

    without blocking the main process without using any multithreading or multiprocessing

    A single thread can't be doing two things at the same time, so... threading is the absolute minimum you need to use in order not to block.