Search code examples
pythonclockalarm

Is there any Python module available which can alarm after certain time


There is a significant difference between my question and the given one. If I implement sleep as given on the link (which some people think my question is a duplicate of another one) then my whole app will hang for certain time. On the other hand I am looking for a scheduler so that my app will not hang but just after a certain period of time a .wav file will run. Meanwhile I would be able to do anything using my app. Hope that makes sense.

I am going to build an alarm clock. I think I can do this according to this Algorithm...

  • take current time using time.clock()
  • compare current time with the given time.
  • if current time is not given time then continue taking current time and compare whether current time is the given time or not.
  • if current time is the given time then play the .wav file.

The problem with this program is it will continuously run until the given time. So I am looking for better idea. Let's say if there is any Python module/class/function which can play a sound file on a given time. Is there any Python module/class/function which can wake up on a given time? Or my algorithm is used usually for all alarm clocks?


Solution

  • Have a look at the sched module.

    Here's an example on how to use it:

    import sched, time, datetime
    
    def print_time():
        print("The time is now: {}".format(datetime.datetime.now()))
    
    # Run 10 seconds from now
    when = time.time() + 10
    
    # Create the scheduler
    s = sched.scheduler(time.time)
    s.enterabs(when, 1, print_time)
    
    # Run the scheduler
    print_time()
    print("Executing s.run()")
    s.run()
    print("s.run() exited")
    
    The time is now: 2015-06-04 11:52:11.510234
    Executing s.run()
    The time is now: 2015-06-04 11:52:21.512534
    s.run() exited