-1

I am trying to make a python program that makes a windows box pop up at certain times to remind me that I have to do something. Problem is, the while loop makes python crash, is there any way to make python check the time without a while loop?

while 1:
    gettime = time.strftime("%H:%M", time.localtime())
    gettime.replace(':','.')

    if gettime in tasks.keys():
        tasks[gettime] = dowat
        ctypes.windll.user32.MessageBoxW(0,u'ALERT!', dowat, 0)
        time.sleep(10)
        SendKeys.SendKeys("""
                {LWIN}
                l
                """)

I tried making python sleep at the end of the loop but it still freezes up.

Katriel
  • 120,462
  • 19
  • 136
  • 170
user1492032
  • 11
  • 1
  • 3
  • The problem's not the `while` loop. Does it crash, or does it freeze up? If it crashes, can you be more specific with what messages you get? – kindall Aug 26 '12 at 19:13
  • 1
    Why not just put it in [Scheduled Tasks](http://support.microsoft.com/kb/308569)? – Katriel Aug 26 '12 at 19:18
  • I wanted to do this as a small project, it just freezes and stops responding – user1492032 Aug 26 '12 at 19:19
  • I fixed your code to what I assume you meant it to be -- is that right? Your indentation was definitely wrong, and I assume you put `gettime` in a variable for a reason. – Katriel Aug 26 '12 at 19:20
  • 1
    Also, I think your "MessageBoxW" call might be blocking execution. Add prints before and after it to figure out whether or not that's the case. – Zoran Pavlovic Aug 26 '12 at 19:45
  • related: [Python timer script doesn't run when set to long periods later](http://stackoverflow.com/questions/12013813/python-timer-script-doesnt-run-when-set-to-long-periods-later) – jfs Aug 26 '12 at 22:40

1 Answers1

1

You're going about it the wrong way... You don't need a while loop. What you need to do is get your current time and work out the time difference. Then you only need to call time.sleep once.

Here's some old python code I had laying around that I used for something like this. It had stuff around it that I had to cleanup/remove, so it might not work 100%.

import time
import datetime

CurrentTime = datetime.datetime.now()

exec_time = "18:00"

val = datetime.datetime.strptime(exec_time, "%H:%M")
val = datetime.datetime(year=CurrentTime.year, month=CurrentTime.month, day=CurrentTime.day, hour=val.hour, minute=val.minute)

if (val > CurrentTime):
    print "val = ", val
    val = datetime.datetime(year=CurrentTime.year, month=CurrentTime.month, day=CurrentTime.day, hour=val.hour, minute=val.minute) - CurrentTime #Calculate dif.

    time.sleep(val.seconds) #Sleep to next event
Zoran Pavlovic
  • 1,166
  • 2
  • 23
  • 38
  • 2
    you could use [datetime.replace(), and should use val.total_seconds(); also threading.Timer() might produce more natural behavior than time.sleep() if computer is hibernated/resumed](http://stackoverflow.com/a/12015233/4279) – jfs Aug 26 '12 at 22:50