Activate a daemon several times a day

Simon Forman rogue_pedro at yahoo.com
Thu Jul 6 12:13:44 EDT 2006


Yves Glodt wrote:
> Hi,
>
> I have a daemon which runs permanently, and I want it to do a special
> operation at some specifiy times every day, consider this configfile
> extract:
>
> [general]
> runat=10:00,12:00
>
>
> What would be the easiest and most pythonic way to do this?
> Something like this pseudocode:
>
> while True:
> 	if now(hours) in runat:
> 		act()
> 		sleep(60)
> 	sleep(10)
>
>
> Please enlighten me!
>
> Best regards,
> Yves

If you're on a unix-ish system, you might consider making your daemon
sensitive to a signal and then use cron and kill to send it that signal
when you want it to activate.  This is just an idea.  It might not be
the kind of solution you're looking for, especially if you're not
already familiar with cron & crontab.


It might be more helpful to you to tell you that you can get the
current hour as an int using the gmtime() (for UTC) or localtime()
(for, uh, local time :-) ) from the time module:

>>> from time import gmtime, localtime
>>> gmtime()
(2006, 7, 6, 16, 6, 32, 3, 187, 0)
>>> gmtime()[3]
16
>>> help(gmtime)
Help on built-in function gmtime in module time:

gmtime(...)
    gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,
                           tm_sec, tm_wday, tm_yday, tm_isdst)

    Convert seconds since the Epoch to a time tuple expressing UTC
(a.k.a.
    GMT).  When 'seconds' is not passed in, convert the current time
instead.

>>> help(localtime)
Help on built-in function localtime in module time:

localtime(...)
    localtime([seconds]) ->
(tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)

    Convert seconds since the Epoch to a time tuple expressing local
time.
    When 'seconds' is not passed in, convert the current time instead.




That takes care of the "now(hours)" part of your pseudocode.


HTH,
~Simon




More information about the Python-list mailing list