Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python scheduling a job starting every weekday and running every hour

I currently have a sample code defined as:

import schedule
import time

def job(t):
    print ("I'm working...", t)
    return

schedule.every().day.at("01:00").do(job,'It is 01:00')

while True:
    schedule.run_pending()
    time.sleep(60) # wait one minute

I am looking to however run the code every hour on weekdays from 9AM to 4PM. i.e. every day Monday through Friday I want to run the code at 9AM, 10AM, ..., 3PM, 4PM.

Reading the documentation for schedule it seems that I can run the code individually Monday through Friday but not only weekday between two specified times.

Also, shouldn't the following time.sleep(60) make the code run perpetually?

like image 909
Zanam Avatar asked Nov 03 '17 00:11

Zanam


3 Answers

The only way it worked for me is this:

import schedule
import datetime
import time

nowtime = str(datetime.datetime.now())

def job(t):
    print("I'm working...", str(datetime.datetime.now()), t)

for i in ["06:00", "09:00", "12:00", "15:00", "18:00"]:
    schedule.every().monday.at(i).do(job, i)
    schedule.every().tuesday.at(i).do(job, i)
    schedule.every().wednesday.at(i).do(job, i)
    schedule.every().thursday.at(i).do(job, i)
    schedule.every().friday.at(i).do(job, i)

while True:
    schedule.run_pending()
    time.sleep(30)
like image 97
Jan Avatar answered Sep 28 '22 06:09

Jan


def weekday_job(x, t=None):
    week = datetime.today().weekday()
    if t is not None and week < 5:
        schedule.every().day.at(t).do(x)

weekday_job(main, '01:00')
weekday_job(main, '02:00')

while True:
    schedule.run_pending()
    time.sleep(60)
like image 43
SPQR Avatar answered Sep 28 '22 07:09

SPQR


You can use library APScheduler. For example:

from apscheduler.schedulers.blocking import BlockingScheduler

def job_function():
    print("Hello World")

sched = BlockingScheduler()

# Runs from Monday to Friday at 5:30 (am) until
sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30)
sched.start()
like image 22
gelkin Avatar answered Sep 28 '22 06:09

gelkin