-2

I'm creating an event notification system for our gaming community. However, I'm not entirely sure where to start.

I have a dictionary of events and their times, for example:

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

The times have already been converted to the correct datetime format using strptime(). What I now need is for the user to be notified when one of these events is about to occur (e.g a 15 minute alert, then a 5 minute alert).

For example:

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

My question is this: How can I get python to wait until an event is near (by comparing the current time, with the event's time), then perform an action (e.g. a notification in my case)?

P.S I'm using Python 2.7.5 (due to lack of API updates)

Dotl
  • 1,406
  • 1
  • 13
  • 16

1 Answers1

0

Try to loop until your check evaluates True:

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

The sleep gives you CPU time for other tasks.

EDIT

Ok, I'm not sure what exactly your question is. First I thought you wanted to know how to let python 'wait' for an event. Now it seems you want to know how to compare event dates with the current date. I think the following is a more complete approach. I think you can fill in the details yourself??

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)
hsmit
  • 3,906
  • 7
  • 34
  • 46
  • Thanks for your answer, but what would myAlertCheck() consist of? I need to ask Python to compare the event's time with the current time, and is it going to be occurring in the next 15 minutes? – Dotl Jun 23 '13 at 09:56
  • @user2513268: I added a 2nd piece of code to help you with date comparison. Does this solve your *main* question? – hsmit Jun 23 '13 at 11:34
  • Ah yes, that answers my question. delta_s was the missing piece. You see, in order for python to **know** it has to wait it would have to compare the event time and the current time. Thanks again. – Dotl Jun 23 '13 at 11:51
  • ok, have a look at the datetime.timedelta module – hsmit Jun 23 '13 at 12:06