简体   繁体   中英

simulate crontab with twisted deferred and looping calls

I would like to implement a cron-like behaviour with my twisted application. I want to trigger a periodic call (let's say every week) but running at a precise time only, not when i start my application.

My use case is the following: my python application is started at any time in the week. I want the calls to be performed every monday at 8am. But I don't want to perorm active waiting (using a time.sleep()), i would like to use callLater to trigger the call next monday and then start a looping call from that date.

any idea/advice? thanks, J.

If you are absolutely in love with cron-style specifiers, you could also consider using parse-crontab

Then your code looks basically like:

from crontab import CronTab
monday_morning = CronTab("0 8 * * 1")

def do_something():
    reactor.callLater(monday_morning.next(), do_something)
    # do whatever you want!

reactor.callLater(monday_morning.next(), do_something)
reactor.run()

If I understood your question correctly you are thinking of first time execution of a scheduled task and how to supply initial start time for the app. If this is a case, you just need to calculate timedelta value in seconds to be passed to callLater.

import datetime
from twisted.internet import reactor

def cron_entry():
    full_weekseconds = 7*24*60*60
    print "I was called at a specified time, now you can add looping task with a full weekseconds frequency"


def get_seconds_till_next_event(isoweekday,hour,minute,second):
    now = datetime.datetime.now()
    full_weekseconds = 7*24*60*60
    schedule_weekseconds = ((((isoweekday*24)+hour)*60+minute)*60+second)
    now_weekseconds=((((now.isoweekday()*24)+now.hour)*60+now.minute)*60+now.second)

    if schedule_weekseconds > now_weekseconds:
        return schedule_weekseconds - now_weekseconds
    else:
        return  now_weekseconds - schedule_weekseconds + full_weekseconds


initial_execution_timedelta = get_seconds_till_next_event(3,2,25,1)
"""
This gets a delta in seconds between now and next Wednesday -3, 02 hours, 25 minutes and 01 second
"""
reactor.callLater(initial_execution_timedelta,cron_entry)
reactor.run()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM