2013-06-23 26 views
-2

我正在爲我們的遊戲社區創建一個事件通知系統。但是,我不完全確定從哪裏開始。Python - 當事件接近時做(某事)

我有要事和他們的時代的字典,例如:使用strptime

{'Game Night': 19:00 2013-06-29, 
'3CB vs ST3 Match': 18:45 2013-07-02, 
'Website Maintainance': 13:00 2013-07-16, 
etc} 

時代已經轉換爲正確的日期時間格式()。我現在需要的是當這些事件之一即將發生時(例如,15分鐘警報,然後是5分鐘警報),通知用戶。

例如:

"NOTICE: 3CB vs ST3 Match will begin in 15 minutes!" 
10 minutes later... 
"NOTICE: 3CB vs ST3 Match will begin in 5 minutes!"

我的問題是這樣的: 我怎樣才能得到蟒蛇等到事件是附近(通過比較當前時間,與事件的時間),然後執行一個動作(例如我的情況是通知)?

PS 我使用Python 2.7.5(由於缺乏API更新)

回答

0

嘗試循環,直到你的檢查判斷爲真:

import time 
interval = 0.2 # nr of seconds 
while True: 
    stop_looping = myAlertCheck() 
    if stop_looping: 
     break 
    time.sleep(interval) 

的睡眠讓你的CPU時間等任務。

編輯

好吧,我不知道你的問題是什麼。首先,我想你想知道如何讓python'等待'一個事件。現在看來你想知道如何比較事件日期和當前日期。 我認爲以下是更完整的方法。我想你可以自己填寫細節?

import time 
from datetime import datetime 

interval = 3 # nr of seconds  
events = { 
    'Game Night': '14:00 2013-06-23', 
    '3CB vs ST3 Match': '18:45 2013-07-02', 
    'Website Maintainance': '13:00 2013-07-16', 
} 

def myAlertCheck(events): 
    for title, event_date in events.iteritems(): 
     ed = datetime.strptime(event_date, '%H:%M %Y-%m-%d') 
     delta_s = (datetime.now() - ed).seconds 
     if delta_s < (15 * 60): 
      print 'within 15 minutes %s starts' % title 
      return True 

while True: 
    stop_looping = myAlertCheck(events) 
    if stop_looping: 
     break 
    time.sleep(interval) 
+0

感謝您的回答,但myAlertCheck()包含哪些內容?我需要讓Python將事件時間與當前時間進行比較,並且是否會在未來15分鐘內發生? – Dotl

+0

@ user2513268:我添加了第二段代碼來幫助您進行日期比較。這是否解決你的*主要問題? – hsmit

+0

啊,是的,這回答我的問題。 delta_s是缺失的部分。你看,爲了讓python知道**必須等待它必須比較事件時間和當前時間。再次感謝。 – Dotl