Is there a way to schedule my script?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Dec 17 18:39:47 EST 2014


Juan Christian wrote:

> I know about the schedule modules and such but they work in situations
> like 'run this in a X hours/minutes/seconds interval', I already have my
> code in a while loop with sleep (it's a bit ugly, I'l change to a
> scheduler soon).
[...] 
> I want my script to start at a given time and stop at another given time,
> is that possible?

The right solution to this is probably to use your operating system's
scheduler to run your script at whatever time or times you want. Under
Unix/Linux, that is cron. I'm sure Windows will have it's own, but I don't
know what it is.

Then your script then doesn't have to care about times at all, it just runs
and does its thing, and the OS controls when it runs. cron is amazingly
flexible.

This is the proper separation of concerns. Your script doesn't have to deal
with memory management, or the file system, or scheduling times, that is
the operating system's job. The OS already has tools to do this, and can do
them *much better than you*. (What happens if your script dies? What about
when the time changes, say because of daylight savings?)

Unless you are running on some primitive OS with no way to control when jobs
run except to manually run them, the *wrong* solution is a busy-wait loop:

while True:
    # Wait forever, doing nothing.
    sleep(0.1)  # Yawn.
    if now() == some_time():
        do_this()


It doesn't matter if you use the sched module to shift the time check to
another part of your code if the main loop does nothing. The critical
question here is this:

While you are waiting for the scheduled time, does your main loop
continuously do any other work? 

If the answer is Yes, then using sched is the right approach.

If the answer is No, then your main loop is just killing time, doing nothing
but sleeping and waiting, like somebody checking their wristwatch every two
seconds. You should simplify your script by getting rid of the main loop
completely and let your OS handle the timing:

# No loop at all.
do_this()


-- 
Steven




More information about the Python-list mailing list