Backend Development 5 min read

Python Scheduled Task Execution Methods: sleep loops, threading.Timer, sched, and schedule library

This article explains multiple Python techniques for running periodic tasks, covering a simple while‑True loop with time.sleep, the threading.Timer class, the built‑in sched module, and the third‑party schedule library, each with code examples and usage notes.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Scheduled Task Execution Methods: sleep loops, threading.Timer, sched, and schedule library

This article demonstrates several ways to execute periodic tasks in Python, including using a while‑True loop with time.sleep() , the threading.Timer class, the sched module, and the third‑party schedule library.

1. Loop with sleep()

from datetime import datetime
import time

def timedTask():
    while True:
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        time.sleep(10)

if __name__ == '__main__':
    timedTask()

This method prints the current time every 10 seconds but keeps the loop active, which may block other operations.

2. threading.Timer

from datetime import datetime
from threading import Timer
import time

def task():
    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

Timer(10, task).start()

Timer schedules a single execution after a delay; repeated execution can be achieved by re‑creating the timer inside the task.

3. sched module

import datetime, sched, time

def task():
    print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(10, 1, task)
scheduler.run()

The sched.scheduler accepts a time function and a delay function, allowing precise control over task ordering and priority.

4. schedule library

import schedule, time

def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)          # every 10 minutes
schedule.every().hour.do(job)              # every hour
schedule.every().day.at("10:30").do(job)   # daily at 10:30

while True:
    schedule.run_pending()
    time.sleep(1)

The library provides a readable DSL for common intervals and also supports passing arguments to the job function.

backend developmenttask schedulingthreadingschedulesched
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.