Python sched Module Tutorial – Event scheduler

The Python sched Module is a library that introduces the ability to schedule events and jobs in Python. The sched Module is part of the Standard Library in Python, which means it needs no external installation. In this Tutorial we will discuss the sched Module, and explain how to schedule, manage and automate events in Python.

The benefit of using an event scheduler like sched, means that it’s platform independent and can run on any OS. This is in contrast to the Windows Task Scheduler for example, which is exclusive to Windows.


Scheduling Tasks with Sched in Python

The very step to scheduling tasks with sched, is to create a scheduler object. Using this object, and can schedule, un-schedule and automate tasks.

To create this scheduler object, we use the following code.

import sched
import time
  
# Creates an instance of the scheduler class
scheduler = sched.scheduler(time.time, time.sleep)

Let’s now try scheduling some tasks.

To schedule an event, we need a function that needs to be called. We simply give the scheduler object the function name, and a time period, and it executes the function after that time period The function that does this, is called enter().

import sched
import time
  
def task():
    print("Execute Task...")
  
# Creates an instance of the scheduler class
scheduler = sched.scheduler(time.time, time.sleep)

scheduler.enter(delay = 3, priority = 1, task)

scheduler.run()

Try running this code for yourself to see the output!

Events that are scheduled for the same time will be executed in the order of priority. The lower the number we passed into the priority parameter, the higher the priority. So 1 is the highest priority, whereas 10 is a pretty low priority.

Now let’s schedule a task, where we execute a function with some parameters. All we need to do is pass in a tuple with all the required arguments. (Be sure to include a comma after the last argument, else there could be issues)

import sched
import time
  
def task(name):
    print("Execute Task:", name)
  
# Creates an instance of the scheduler class
scheduler = sched.scheduler(time.time, time.sleep)

scheduler.enter(3, 1, task, ("Open Browser",))

scheduler.run()

There is a variant of the enter() function, which just has one difference. Instead of taking a “time delay” as the first parameter, it takes a specific time at which it will execute the function. So if you want it to execute 5 seconds later, instead of passing 5, you will pass in time.time() + 5, which is 5 second ahead of the current time.

import sched
import time
  
def task(name):
    print("Execute Task:", name)
  
# Creates an instance of the scheduler class
scheduler = sched.scheduler(time.time, time.sleep)

scheduler.enterabs(time.time()+5, 1, task, ("Open Browser",))

# Run all scheduled events
scheduler.run()

Removing Scheduled Events

Now that we know how to schedule tasks, let’s take a look at how to remove them.

Whenever you create a job using either the enter() or enterabs() functions, a job object is returned. You can use this object to later cancel the task if you wish. All we need to do is pass this object into the cancel(obj) method.

import sched
import time
  
def task(name):
    print("Execute Task:", name)
  
# Creates an instance of the scheduler class
scheduler = sched.scheduler(time.time, time.sleep)

job1 = scheduler.enterabs(1, 1, task, (1,))
job2 = scheduler.enterabs(2, 2, task, (2,))
job3 = scheduler.enterabs(2, 1, task, (3,))

scheduler.cancel(job1)

scheduler.run()
Execute Task: 3
Execute Task: 2

In the above example, only job2 and job3 are executed, as job1 was cancelled. Job3 executes first, as it has a higher priority.


Other Functions in the Python Sched Module

Let’s take a look at a bunch of other functions and attributes from the sched Module.

The queue attribute returns a list of all currently scheduled tasks. It also provides information regarding their parameters and their values.

import sched
import time
  
def task(name):
    print("Execute Task:", name)
  
# Creates an instance of the scheduler class
scheduler = sched.scheduler(time.time, time.sleep)

job1 = scheduler.enterabs(1, 1, task, (1,))
job2 = scheduler.enterabs(2, 2, task, (2,))
job3 = scheduler.enterabs(2, 1, task, (3,))

print(scheduler.queue)

scheduler.run()
[Event(time=1, priority=1, action=<function task at 0x00000234C26EE708>, argument=(1,), kwargs={}),
 Event(time=2, priority=1, action=<function task at 0x00000234C26EE708>, argument=(3,), kwargs={}),
 Event(time=2, priority=2, action=<function task at 0x00000234C26EE708>, argument=(2,), kwargs={})]

We also have the empty() function, which returns True if there are no scheduled events in the queue. Otherwise it returns false.

import sched
import time

# Creates an instance of the scheduler class
scheduler = sched.scheduler(time.time, time.sleep)
  
def task():
    print(scheduler.empty())

job1 = scheduler.enterabs(1, 1, task)
job2 = scheduler.enterabs(2, 2, task)
job3 = scheduler.enterabs(2, 1, task)

scheduler.run()
False
False
True

Other Scheduling Libraries

The schedule library is one of many scheduling and automation libraries in Python. To expand your arsenal and acquire more options check out some of these alternative Scheduling libraries that can be used.

  1. Python schedule Library
  2. Python Advanced Scheduler

This marks the end of the Python sched Module 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
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments