Schedule jobs with schedule module

Posted by Afsal on 01-Dec-2023

Hi Pythonistas!

Today we will learn a package called schedule. This module is used to run python functions periodically using friendly syntax. Let us check what are the features of this package.

  • A simple to use API for scheduling jobs, made for humans.
  • In-process scheduler for periodic jobs. No extra processes needed!
  • Very lightweight and no external dependencies.
  • Excellent test coverage.
  • Tested on Python and 3.7, 3.8, 3.9, 3.10, 3.11

Installation

pip install schedule

Code

import schedule
import time

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

schedule.every(10).seconds.do(job)
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every(5).to(10).minutes.do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().day.at("12:42", "Europe/Amsterdam").do(job)
schedule.every().minute.at(":17").do(job)

def job_with_argument(name):
    print(f"I am {name}")

schedule.every(1).seconds.do(job_with_argument, name="Peter")

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

schedule.every(10).seconds.do(job) - This will run the code every 10s. Every 10 we get “I’m working” on our terminal

schedule.every(10).minutes.do(job) - This will run the code every 10 minutes.

schedule.every().hour.do(job) - This will run the code every hours

schedule.every().day.at("10:30").do(job) - This will run the code every day at 10:30.

Note: Time in 24 hours format

schedule.every(5).to(10).minutes.do(job) - This will run the code at irregular (random) intervals. But the random value N is such a way the 5<= N <= 10

schedule.every().monday.do(job) - This will run the code on every monday

schedule.every().wednesday.at("13:15").do(job) - This will run the code on every wednesday at 13:15

schedule.every().day.at("12:42", "Europe/Amsterdam").do(job) - This will run the code at 12:42 in Amsterdam timezone

schedule.every().minute.at(":17").do(job) - This will run the code on every minute at 17th seconds

Schedule a function with argument

schedule.every(1).seconds.do(job_with_argument, name="Peter") - Here name is the argument to the function job_with_argument any arguments can be passed as keyword argument 

Code

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

schedule.run_pending() - Check for the pending jobs and runs.

For more information you can visit the official link

Hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in