How to import a python file to be executed on schedule time. using schedule

I am trying to use schedule to schedule jobs every work day at a certain time and execute a file when its time. The problem is that it runs the validate.py on schedule and off schedule. I want it to run only when the time is 9:09 .

from dateutil import rrule
from datetime import datetime, timedelta
import time
import schedule
import requests
import validate.py

def job():
    execfile("validate.py")


start_hour = datetime.strptime("09:09:26","%H:%M:%S")
end_hour = start_hour + timedelta(hours=7)

for t in rrule.rrule(rrule.HOURLY, dtstart=start_hour, until=end_hour):
    schedule.every().monday.at(t.strftime("%H:%M")).do(job)
    schedule.every().tuesday.at(t.strftime("%H:%M")).do(job)
    schedule.every().wednesday.at(t.strftime("%H:%M")).do(job)
    schedule.every().thursday.at(t.strftime("%H:%M")).do(job)
    schedule.every().friday.at(t.strftime("%H:%M")).do(job)

while True:
    schedule.run_pending()
    time.sleep(1)
 

Answer

import pytz
from apscheduler.schedulers.blocking import BlockingScheduler

def job():
    execfile("validate.py")

if __name__ == '__main__':
    timez = pytz.timezone(YOUR_TIMEZONE)
    scheduler = BlockingScheduler(timezone=timez)
    scheduler.add_job(job, "cron", day_of_week="1-5", hour=9, minute=9)
    scheduler.start()

BlockingScheduler might be useful on your case. the parameter: YOUR_TIMEZONE just like'Asia/Shanghai'

Leave a Reply

Your email address will not be published. Required fields are marked *