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.
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.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.