Sling Academy
Home/Python/Python: Schedule events with sched.scheduler class (3 examples)

Python: Schedule events with sched.scheduler class (3 examples)

Last updated: August 03, 2023

This succinct, example-based article is about the sched.scheduler class in Python, which can be super helpful for automation systems.

The Fundamentals

The sched module was added to Python in version 1.5.2, which was released on April 13, 1999. The sched.scheduler class was part of this module since then, so you don’t have to install any third-party libraries to use it.

The sched.scheduler class is used for scheduling events that need to run at specific times or after certain delays. It provides a generic interface to create and manage a queue of events, and execute them according to their priorities and scheduled times.

Constructor

Syntax:

class sched.scheduler(timefunc=time.monotonic, delayfunc=time.sleep)

The class constructor takes two optional parameters:

  • timefunc is a function that returns the current time in any units.
  • delayfunc is a function that takes a time argument and delays that many time units. By default, the class uses time.monotonic and time.sleep from the time module.

Main methods

The sched.cheduler class brings to the table four main methods for scheduling and managing events:

  • enterabs(time, priority, action, argument=(), kwargs={}): This one schedules a new event to run at an absolute time specified by the time argument. The priority argument determines the order of execution for events at the same time. The action argument is the function to be executed when the event occurs and the action argument and kwargs arguments are the positional and keyword arguments for the action function.
  • enter(delay, priority, action, argument=(), kwargs={}): This method schedules a new event to run after a relative delay specified by the delay argument. The other arguments are the same as for the enterabs method.
  • cancel(event): This method removes an event from the queue. The event argument is an object returned by either the enterabs or enter method.
  • run(): This method runs the events in the queue until it is empty. It blocks the current thread until all events are executed or canceled.

Use cases & limitations

The sched.scheduler class can be used for various purposes, such as creating timers, alarms, bots, automation scripts, etc. However, it has some limitations that should be considered before using it:

  • It is not thread-safe in Python versions before 3.3, which means it can cause errors or unexpected behavior if used in multi-threaded environments (if you’re using a modern version of Python, there is no need to worry about this point).
  • It cannot insert a new event before the one currently pending in a running scheduler, which means it cannot handle dynamic changes in the event queue.
  • It holds up the main thread until the event queue is empty, which means it can block other tasks or operations from running.

Words can make you get bored quickly. Let’s write some code to make our hands dirty and warm our heads.

Examples

Scheduling a function to run after an amount of time

This example creates a simple timer that prints some messages after 10 seconds:

# SlingAcademy.com
# This code uses Python 3.11.4

import sched
import time

# Create a scheduler instance
scheduler = sched.scheduler(time.time, time.sleep)


# Define a function to print a message
def print_message():
    print("Time's up!")
    print("Welcome to Sling Academy!")


# Schedule the function to run after 10 seconds
scheduler.enter(10, 1, print_message)

# Start the scheduler
scheduler.run()

Output (that shows up after a delay):

Time's up!
Welcome to Sling Academy!

A simple bot that fetches data from an API periodically

In this example, we will create a simple bot that can get information from the internet every 30 seconds. You’ll need to install the requests module first:

pip install requests

The code:

# SlingAcademy.com
# This code uses Python 3.11.4

import sched
import time
import requests
from datetime import datetime

# Create a scheduler instance
scheduler = sched.scheduler(time.time, time.sleep)


# Define a function to fetch data from an API
def fetch_data():
    # Use the requests module to get data from an API
    response = requests.get("https://api.slingacademy.com/")
    # Print the status code and the JSON data
    print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("Status code:", response.status_code)
    print("Data:", response.json())
    # Schedule the function to run again after 30 seconds
    scheduler.enter(10, 1, fetch_data)


# Schedule the function to run for the first time
scheduler.enter(0, 1, fetch_data)

# Start the scheduler
scheduler.run()

You’ll see something like this:

Time: 2023-08-03 17:55:24
Status code: 200
Data: {'success': True, 'message': 'Welcome to Sling Academy Public API'}
Time: 2023-08-03 17:55:35
Status code: 200
Data: {'success': True, 'message': 'Welcome to Sling Academy Public API'}
Time: 2023-08-03 17:55:45
Status code: 200
Data: {'success': True, 'message': 'Welcome to Sling Academy Public API'}

A program that does something every midnight

There are tasks that you want to be automatically done every night (or another time frame), such as backup data, sending emails, etc. Here’s how to achieve that goal:

# SlingAcademy.com
# This code uses Python 3.11.4

import sched
import time

# Create a scheduler instance
scheduler = sched.scheduler(time.time, time.sleep)


# Define a function to do something
def do_something():
    # Print a message
    print("Hello, it's midnight!")
    # Do other things here

    # Schedule the function to run again at the next midnight
    scheduler.enterabs(time.time() - (time.time() % 86400) + 86400, 1, do_something)


# Schedule the function to run for the first moment at midnight
scheduler.enterabs(time.time() - (time.time() % 86400) + 86400, 1, do_something)

# Start the scheduler
scheduler.run()

Conclusion

You’ve learned the fundamentals of the sched.scheduler class in Python. With this knowledge in mind, you can automate some of your daily boring tasks and have more time to spend with your beloved people. If you find something outdated or incorrect, please let me know by leaving a comment. I’ll recheck and update the article as needed. The tutorial ends here. Happy coding & have lot of fun with Python programming!

Next Article: Python: Crawling HTML tables and save to CSV files

Previous Article: Python: Checking System RAM/CPU/Disk Usage

Series: Python – Fun Examples

Python

You May Also Like

  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types
  • Python: Typing a function with *args and **kwargs