Scheduling in Python with the sched module

Sched Python Min

Let’s talk about the sched module in Python. While working with the datetime module in Python, you must have come across a feature that you wish you could have and use in Python, that is, scheduling.

Event scheduling, a purposeful scheduling task that could be used to alert or perform events based on the input of time or date.

Scheduling was thought of in the past as well, and as such, we now have, ready to use, the sched module.

We’ll be exploring the various uses, and the use cases of this module in this article, but, we’ll be working with the time module for simplicity.

In case you find anything confusing while working with your own version of the sched module, you might want to look into our article on working with the datetime module for a quick recap on datetime objects.

Installing the sched module in Python

You’d be surprised to hear it, but, there’s no need for installation or a package manager for this module, as it shows up by default in the standard library for Python.

Even in the documentation too! In case you wish to visit it for a clearer perspective on the arguments and keywords, you can find the link in the references at the bottom of this article.

How to use the sched module?

A pre-requisite to working with the sched module is to have a basic understanding of datetime/time objects.

If you’ve worked with the datetime module or just the time module beforehand, you might be pleased to know that the sched module acts as an extension of datetime, much like another module, dateutil.

1.0 Scheduler – Importing the sched module

The sched module as a whole consists of only one class, and in case you wish to verify it for yourself, here’s the source code.

So, what does this mean for us?

Well, in short, there’s only one class, and so, we’ll only be creating one object which can utilize all of the features of the scheduler class.

This class is known as the scheduler. We can get started right away, but, before we get started, we’ll want to first import the module to work with it.

import sched, time

1.1 How to create a scheduler object

Creating the scheduler object is pretty straightforward, and after importing the sched module, there’s really only one line you’ll need to write to use it.

# Intializing s as the scheduler object
s = sched.scheduler(time.time, time.sleep)

This one line provides you with the functionality of the time module to work with time, and even provides a delay, supporting multi-threading operations.

This essentially creates a variable s, which is created as an object of the class scheduler of the sched module.

1.2 Working with the scheduler object

Here on out, we’ll be using the functionality provided to work with printing out a bunch of time objects, and the time at which the operation was performed itself.

In this tiny snippet, we’re working with the crux of the sched module, creating, and entering events.

Much like when we work with threads, in the sched module, we use the run method to run all the tasks which were scheduled to be run.

# Creating a method to print time
def print_time(a="default"):
    print("From print_time", time.time(), a)

# Method to print a few times pre-decided
def print_some_times():
    print("This is the current time : ", time.time())

    # default command to print time
    s.enter(10, 1, print_time)

    # passing an argument to be printed after the time
    s.enter(10, 1, print_time, argument=('positional',))

    # passing a keyword argument to print after the time
    s.enter(10, 1, print_time, kwargs={'a': 'keyword'})

    # runs the scheduler object
    s.run()
    print("Time at which the program comes to an end: ", time.time())

# Output
# This is the current time :  1609002547.484134
# From print_time 1609002557.4923606 default
# From print_time 1609002557.4923606 positional
# From print_time 1609002557.4923606 keyword
# Time at which the program comes to an end :  1609002557.4923606

A thing to pay attention to would be the run method that was used with the scheduler object. This is a function that runs all of the scheduled events, and will also wait based on the time provided by the delayfunc parameter.

This delves a lot more into the concept of concurrency and multi-threading, with the concepts of start, run, wait, and notify, and is quite a fun read if you’re interested.

Along with this, you might have noted the few arguments, these were added in to showcase the distinction between the print statements.

1.3 Additional features

There do exist a few more functions that we haven’t necessarily looked into in this example, consisting of the cancel, empty, and queue functions.

  • The cancel function is used to remove a particularly provided event from the queue.
  • The empty function is used to return a boolean response on the state of the queue, and whether or not it is empty.
  • The queue function provides us with a list of the available/upcoming events in the order that they will be run. Each event a named tuple consisting of the details of the event.

Conclusion

As you can see, the doorways that this standard module provided by Python is quite the reveal, and could potentially help you work on a lot more good features as an addition or the frame for your code!

In case you wish to work with this module in the future, don’t hesitate to open up this article as a reference while you work on the code.

Going through the documentation can be a daunting task, and that’s why we’ve tried to help you navigate through them with user friendly articles.

Check out our other articles on the different modules that we’ve covered, datetime, dateutil, psutil, and our all time favourite data science tool, pandas!

References