dbader / schedule

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

Pass in day name #574

Open jamesgeddes opened 1 year ago

jamesgeddes commented 1 year ago

Firstly, thanks for writing schedule! It is fantastic and I have used it a tonne.

I am getting user input to ascertain which days the program should execute. Though I never normally trust a user, for the sake of simplicity here, we shall assume that the user is infallible.

day_name = input("Day: ")

The docs show that one can specify days to run a function on as follows.

 schedule.every().monday.do(job)
 schedule.every().wednesday.at("13:15").do(job)

Unfortunately, I cannot see a way to pass a day name or value into schedule. As such, I am currently running a "check day" job every day.

def check_day():
    day_today = datetime.today().strftime("%A")
    if day_today.lower() != str(input_day).lower():
        return
    schedule.every().day.at(go_time).do(job)

def main():
    schedule.every().day.at("00:01").do(check_day)
    while True:
        n = schedule.idle_seconds()
        if n is None:
            # no more jobs
            break
        elif n > 0:
            # sleep exactly the right amount of time
            sleep(n)
        schedule.run_pending()

This seems a bit inefficient, particularly when there is nothing to do for several days.

TL;DR

It would be great to be able to pass in a day name or number as a variable.

SearchDream commented 1 year ago

You methods seems will introduce duplicated jobs after 1 month.

luster commented 1 year ago

i'm running into the same thing. without patching the library specifically, you can do something somewhat hacky like the following:

e = schedule.every()
e.start_day = day_name
e.unit = "weeks"
e.at(go_time).do(job)

the day of week properties are setting start_day and unit on the Job object, so this effectively accomplishes the same thing. would be great if the library had a method day_of_week(day_name) that effectively did the same setting of start_day and unit=weeks

mohana-martin commented 12 months ago

@jamesgeddes I use the following solution: getattr(schedule.every(5), "seconds").do(lambda: print("Test"))

For your case, replace the "seconds" with the user input. You can also first check whether the user input is actually valid by checking if it exists in in the Job class, i.e.: "seconds" in schedule.every().__dir__() and repeat asking your user until you don't get a valid response.

Well and of course don't forget to .lower() the user input first.