Using Python sched Module for Task Scheduling

The time.sleep() function pauses program execution for a specified number of seconds, temporarily yielding CPU resources before resuming.

import time

for iteration in range(3):
    print(f"Iteration count: {iteration}")
    time.sleep(8)

This code prints an iteration count every 8 seconds, which works well for basic scenarios. For more structured scheduling needs, Python's built-in sched module provides a robust alternative.

import time
import sched

# Initialize scheduler with time retrieval and delay functions
task_queue = sched.scheduler(time.time, time.sleep)

def log_event(label, timestamp):
    print(f"Execution time: {time.time():.2f} | Label: {label} | Scheduled timestamp: {timestamp:.2f}")

print(f"Queue initialization time: {time.time():.2f}")
current_stamp = time.time()
task_queue.enter(1.5, 2, log_event, ("low-priority", current_stamp))
task_queue.enter(1.5, 0, log_event, ("high-priority", current_stamp))
task_queue.enter(3.0, 1, log_event, ("medium-priority", current_stamp))
task_queue.run()
print(f"Queue empty time: {time.time():.2f}")

Sample output (timestamps will vary):

Queue initialization time: 1718945621.33
Execution time: 1718945622.83 | Label: high-priority | Scheduled timestamp: 1718945621.33
Execution time: 1718945622.83 | Label: low-priority | Scheduled timestamp: 1718945621.33
Execution time: 1718945624.33 | Label: medium-priority | Scheduled timestamp: 1718945621.33
Queue empty time: 1718945624.33

The sched.scheduler constructor takes two callables: one to return the current time, and another to pause execution. The scheduler instance acts as a container for pending tasks. Tasks are added with enter(), and only execute after calling run(). The scheduled timestamp remains static because it is captured when enter() is invoked, not when the task runs. The enter() method has four parameters:

  • delay: Integer or float representing seconds to wait before execution
  • priority: Integer where lower values indicate higher execution precedence for tasks scheduled at the same time
  • action: Callable to execute
  • arguments: Tuple of positional arguments for action; wrap single arguments in parentheses with a trailing comma, e.g., (single_arg,), and use an empty tuple () for no arguments

Tags: python scheduling sched module task automation

Posted on Wed, 13 May 2026 22:21:25 +0000 by C_Calav