Python schedule library – scheduling Tasks and Jobs

The Python Schedule Library is a way of easily scheduling simple tasks in a very minimalistic and user-friendly way.

How to use the Schedule Library?

The Schedule Library has 4 important functions that are used together to schedule tasks.

  1. The every(interval) function is used to start a job that will repeat periodically. The default interval value is 1.
  2. The at(string) function is used to schedule a job at a specific time. The format for the string parameter is HH:MM:SS, where H is the hours, M is the minutes and S is seconds. It is not required to include all three at once. e.g: :MM is for minute jobs, and :SS for second jobs. L
  3. The to(n) function takes an integer as parameter, and generates a random value from it’s initial range to “n”. For example, every(A).to(B).seconds executes the job function every N seconds such that A <= N <= B
  4. The do(func_name, **parameters) is the function that executes the function to be called. The function name is the first parameter in the do() function. Any arguments to be passed to the calling function, are included from the second parameter onwards in the do() function.

Scheduling Jobs with the Schedule Library

Now let’s take a look at some basic examples.

import schedule
import time

def task():
    print("Executing Job...")

# Execute this task every 5 seconds/minutes/hours/days/weeks
schedule.every(5).seconds.do(task)
schedule.every(5).minutes.do(task)
schedule.every(5).hours.do(task)
schedule.every(5).days.do(task)
schedule.every(5).weeks.do(task)

# Execute task every Monday
schedule.every().monday.do(task)

# Execute task on Wednesday at 11:45:20
schedule.every().wednesday.at("11:45:20").do(task)

# Run task every hour at the 30th minute
schedule.every().hour.at(":30").do(task)

# Execute job every 5 - 10 seconds (randomized)
schedule.every(5).to(10).minutes.do(task)

# Runs code in an infinite loop
while True:
    schedule.run_pending()
    time.sleep(1)

Here’s another example, this time using a function with parameters.

import schedule
import time

def prompt(name):
    print("Hello", name)

# Execute this task every 5 seconds
schedule.every(5).seconds.do(prompt, "Coder")

# Runs code in an infinite loop
while True:
    schedule.run_pending()
    time.sleep(1)

Schedule does not account for the time it takes for the job function to execute. Hence this can introduce some inconsistencies if you are not careful. To mitigate this problem, move all long computation off the main thread where the Scheduler functions are called.


How to Cancel Jobs

Knowing how to cancel jobs is as important as knowing how to schedule them. Let’s take a look at the various methods we can use to do so.

The first example uses the cancel_job(obj) function, which takes the job object that we created, and removes it from the scheduler.

def prompt(name):
    print("Hello", name)

# Execute this task every 5 seconds
job = schedule.every(5).seconds.do(prompt, "Coder")
schedule.cancel_job(job)

To clear the scheduler of all jobs in it, simply use the schedule.clear() function.

schedule.clear()

To return all current jobs, call the schedule.get_jobs() function. You can also use this iterate over each job, and clear them one by one from the list.

jobs = schedule.get_jobs()

Using Tags with Jobs

Applying tags when scheduling jobs can come in handy later on. Tags allow you to filter through all jobs and return the job objects for those jobs with a specific tag. To apply a tag, all we need to do is use the tag() function.

import schedule
import time

def task(ID):
    print("Execute Task:", ID)

schedule.every().hour.do(task, 100).tag('hourly_task')
schedule.every().hour.do(task, 101).tag('hourly_task')
schedule.every().day.do(task, 102).tag('daily_tasks')
schedule.every().week.do(task, 103).tag('weekly_task')

hourly_tasks = schedule.get_jobs('hourly_task')
print(hourly_tasks)
[Every 1 hour do task(100) (last run: [never], next run: 2022-02-10 14:36:54),
 Every 1 hour do task(101) (last run: [never], next run: 2022-02-10 14:36:54)]

As you can see, both of the tasks which were tagged as “hourly_task” were returned. You may give a job multiple tags within the same tag() function, separated by commas.

You can also use tags together the clear() function, and clear only those jobs with a specific tag.

# Removes all jobs with the tag, "daily_task"
schedule.clear('daily_task')

Other Scheduling Libraries

The schedule library is primarily aimed towards the scheduling of simple tasks. For more complex situations, we have some alternative Scheduling libraries that can be used.

  1. Python sched Module
  2. Python APScheduler

This marks the end of the Python Schedule Library Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments