dbader / schedule

Python job scheduling for humans.
https://schedule.readthedocs.io/
MIT License
11.73k stars 959 forks source link

using schedule python library to set a Timer #525

Closed kamelel closed 1 year ago

kamelel commented 2 years ago

Excuse me if you find that my question is stupid. I need your help to figure out a way to use the schedule python library to make a led ON for example for 2 minutes an OFF for example for 100 minutes all days (all the time). PS : without using sleep method.

Any hint will be greatly appreciated Thanks in advance

SijmenHuizenga commented 1 year ago

Hi @kamelel, don't worry about asking stupid questions. Might be a bit late for you, but maybe this helps someone else out :)

import schedule

def led_off():
    print("Turn LED off")
    return schedule.CancelJob

def led_on():
    print("Turn LED on")
    # 2 minutes after turning the led ON, turn it OFF
    schedule.every(2).minutes.do(led_off)

# Every 102 minutes, turn the LED ON
schedule.every(102).minutes.do(led_on)

while True:
    schedule.run_pending()
    time.sleep(1)  # This sleep is just to avoid excessive CPU usage

This code schedules the led_on function to run every 102 minutes, and then schedules the led_off function to run 2 minutes after the LED is turned on. The return schedule.CancelJob in the led_off function ensures that the led_off job is removed from the schedule after it has been executed.