Search code examples
pythontimealarmbeep

Python, writing a very basic alarm clock


I've just written a very basic alarm clock in python to warn me when some food is cooked at 2:15pm, but I've read somewhere that time.sleep loses time when other programs are being processed, what should I use instead? My current code, it's really basic -

import time
import winsound
time.sleep(370800)
winsound.Beep(1000,10000)

Solution

  • Do periodic checks. The code below should be ok. You can tweak timeout variable to your needs:

    timeout = 10
    target = time.time() + 370800
    
    while True:
        diff = target - time.time()
        if diff < timeout:
            if diff > 0:  # highly unlikely that diff will go below 0 but just in case
                time.sleep(diff)
            break
        else:
            time.sleep(timeout)
    
    winsound.Beep(1000,10000)