Is there a way to schedule my script?

Juan Christian juan0christian at gmail.com
Wed Dec 17 20:04:18 EST 2014


On Wed Dec 17 2014 at 9:40:52 PM Steven D'Aprano <
steve+comp.lang.python at pearwood.info> wrote:

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

Thanks. That was a great answer. I'll redo my code. It's running and will
only run in my Docker container (Ubuntu Server 14.04.1) so I'll use cron.

Indeed, currently I'm using something like that:

while True:
    if 9 < datetime.now().hour < 24:
        # do stuff
        sleep(randint(3, 6) * 60)
    else:
        # see you in 9 hours
        sleep(9 * 60 * 60)

I knew it wasn't a good approach, but as least it was running as intended!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20141218/cf5fe272/attachment.html>


More information about the Python-list mailing list