[Tutor] Alarm Clock (suggestions please)
john at fouhy.net
Tue Feb 3 05:13:09 CET 2009
2009/2/3 David <david at abbottdavid.com>:
> mytime = list(time.localtime())
> hour = mytime
> minute = mytime
> if hour == alarmhour and minute == alarmmin:
> subprocess.call('mplayer -loop 9 ring.wav', shell=True)
What you've written here is called a Busy Wait -- essentially, your
program will be checking the local time as fast as it possibly can,
which could be hundreds or thousands of times per second. It will
cause your CPU (or, at least, the core python is on) to run at 100%.
I imagine you don't actually care if your alarm is a few milliseconds
late, so you could add a call to time.sleep(1) to the body of the
loop. This will cause python to sleep for one second every iteration,
thus allowing other programs to get some CPU time, and saving your
(in fact, since you're only specifying hour and minute for your alarm,
you may as well sleep for 60 seconds each iteration)
Also, you could just write while(True). Your control variable doit
isn't actually doing anything in this program.
Regarding error checking, you could do tests to make sure the hour and
minutes are in-range. Perhaps you could add code to check whether the
alarm time is more than a certain number of hours in the future.
Depends how complex you want to make it.
(you could also inspect sys.argv -- this would allow you to specify
the time on the command line, rather than requiring user input)
More information about the Tutor