i've written script creates threads sleep until time of day before sending email. run @ 4pm on day script run, others run @ 7am next morning.
my problem threads supposed run @ 4pm won't run until 5pm or 6pm, whereas ones @ 7am run right on time. script typically started between 10am-1pm. i'm using python 2.6.6
the code, in nutshell, follows:
from datetime import datetime, timedelta import threading def main(): today = datetime.now() today_at_4pm = today.replace(hour=16, minute=0, second=0) tomorrow = today + timedelta(days=1) tomorrow_at_7am = tomorrow.replace(hour=7, minute=0, second=0) message = "some message" threading.thread(target=dispatchemail, args=(message, today_at_4pm)).start() threading.thread(target=dispatchemail, args=(message, tomorrow_at_7am)).start() def dispatchemail(message, time_to_send): = datetime.now() if < time_to_send: time_diff = time_to_send - diff_in_seconds = (time_diff.days * 86400) + time_diff.seconds sleep(diff_in_seconds) sendemail(message) def sendemail(message): print message if __name__ == '__main__': main() i can't pin down problem because it's inconsistent when sends , don't have problem running on short time periods. diff_in_seconds calculation appears accurate.
i think error lies in sleep part or in misunderstanding of how threads work. appreciated.
for think should seperate scripts , use crontasks -- i'd prefer not because of how actual contents of message being read/tracked files.
update
i found threading.timer method via python sched docs. allows me run function after period of time. moved sleep time calculation out of dispatchemail allowed me rid of it:
def timedifference(now, time_to_send): if < time_to_send: time_difference = time_to_send - return (time_difference.days * 86400) + time_difference.seconds else: return 0 time_until_4pm = timedifference(datetime.now(), today_at_4pm) time_until_7am = timedifference(datetime.now(), tomorrow_at_7am) threading.timer(time_until_4pm, sendemail, (message)) threading.timer(time_until_7am, sendemail, (message)) are there nuances need aware about?
don't use thread sleeping. absolutely wrong approach problem. if don't want use crons (i assume mean literal linux cron jobs), use https://docs.python.org/2/library/sched.html
Comments
Post a Comment