儘管使用普通的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