简体   繁体   中英

Python - Schedule: Run function every hour + "on the hour"

I'm trying to use the schedule module to do some basic scheduling in a continuously updating script.

Is there a way to set a schedule to run every "x" hours, 'on the hour'?

For example, I'd like to have a function that runs at: [1:02pm, 2:02pm, 3:02pm, 4:02pm] regardless of when I run the script in the first place. In other words, simply doing "schedule.every(1).hours.' doesn't work because I can't guarantee what time the script is run in the first place.

Thanks!

Here you can find examples for case you trying to achieve.

schedule.every().hour.at(":02").do(job)

Here is a simple script:

from datetime import datetime
import time

# scheduled hours in 24-hour format
hours = ["13:2", "14:2", "15:2", "16:2"]

# your function
def foo():
    pass

while True:
    now = datetime.now() # gets current datetime

    hour = str(now.hour) # gets current hour
    minute = str(now.minute) # gets current minute
    current_time = f"{hour}:{minute}" # combines current hour and minute

    # checks if current time is in the hours list
    if current_time in hours:
        foo()
    
    time.sleep(60) # waits a minute until it repeats

Please note that it will check every minute at the same time when you ran it, and not when the new minute starts. (For instance, if you run it in the middle of the minute, it will check again in the middle of the next minute)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM