尽管使用普通的datetime
python模块,您将能够实现您所需的所有功能,但功能更强大的python-dateutil扩展可用,特别是在需要处理重复性事件时。下面的代码应该给你如何实现你的目标指示:
from datetime import *
from dateutil.rrule import rrule, YEARLY
# GLOBAL CONFIG
td_8am = timedelta(seconds=3600*8)
td_jobfrequency = timedelta(seconds=3600) # hourly job
# USER DATA::
# birthday: assumed to be retrieved from some data source
bday = date(1960, 5, 12)
# reminder delta: number of days before the b-day
td_delta = timedelta(days=6)
# difference between the user TZ and the server TZ
tz_diff = timedelta(seconds=3600*5) # example: +5h
# from current time minus the job periodicity and the delta
sday = date.today()
# occr will return the first birthday from today on
occr = rrule(YEARLY, bymonth=bday.month, bymonthday=bday.day, dtstart=sday, count=1)[0]
# adjust: subtract the reminder delta, fixed 8h (8am) and tz difference
occr -= (td_delta + td_8am + tz_diff)
# send the reminder when the adjusted occurance is within this job time period
if datetime.now() - td_jobfrequency < occr < datetime.now():
print occr, '@todo: send the reminder'
else:
print occr, 'no reminder'
而且我建议你不要储存明年提醒日期,因为delta
可能会改变,或者timezone
可能会改变,甚至birthday
本身,所以你需要重新计算它。上面的方法基本上可以即时计算提醒日期(和时间)。
我可以建议的另一件事是存储上次提醒已发送的日期(包括当年的生日)。因此,如果系统停机,您不会错过提醒,但会发送所有尚未发送的提醒。您需要修改代码才能进行额外的检查和更新。
来源
2010-05-05 21:25:43
van
这是我的第一个计划,但我认为如果我有50000警报(db)检查每个小时它将显然是低效率Vs只提取我知道我必须发送。 或者我应该做一个混合,并检查所有警报日间+7之间。 – coulix 2010-05-05 20:05:53