Multiple Ways to Implement Scheduled Tasks in Python
This article introduces eight practical Python solutions for creating scheduled tasks, ranging from simple time.sleep loops to advanced libraries like APScheduler, Celery, and system tools such as cron, each accompanied by clear code examples and usage explanations.
Scheduled tasks are a common requirement in programming, allowing actions to run at predefined times. In Python, there are many ways to achieve this, from built‑in modules to third‑party libraries and operating‑system tools.
Solution 1: Using time.sleep()
Combine time.sleep() with a loop to create a simple periodic task.
import time
def task():
print("Task running...")
while True:
task()
time.sleep(60) # sleep 1 minuteResult:
Task running...
Task running...
Task running...Solution 2: Using the sched module
The sched module provides a flexible event scheduler that can handle multiple tasks.
import time, sched
s = sched.scheduler(time.time, time.sleep)
def task(sc):
print("Task running...")
s.enter(3600, 1, task, (s,))
s.run()Solution 3: Using APScheduler
APScheduler is a powerful library supporting interval, cron, and date‑based scheduling.
from apscheduler.schedulers.blocking import BlockingScheduler
def task():
print("Task running...")
scheduler = BlockingScheduler()
scheduler.add_job(task, 'interval', hours=1)
scheduler.start()Solution 4: Using Celery
Celery is a distributed task queue that can schedule periodic jobs.
from celery import Celery
app = Celery('myapp', broker='pyamqp://guest@localhost//')
@app.task
def my_task():
print("Task running...")
my_task.apply_async(countdown=3600)Solution 5: Using OS cron
On Linux/Unix, create a Python script and schedule it with cron.
# my_task.py
def my_task():
print("Task running...")
if __name__ == "__main__":
my_task()Add to crontab:
0 * * * * /usr/bin/python /path/to/my_task.pySolution 6: Using the schedule library
import schedule, time
def mtask():
print("Task running...")
schedule.every(1).hour.do(mtask)
while True:
schedule.run_pending()
time.sleep(1)Solution 7: Using threading.Timer
import datetime
from threading import Timer
def do():
now = datetime.datetime.now()
print(now)
loop()
def loop():
t = Timer(5, do)
t.start()
if __name__ == "__main__":
loop()Solution 8: Using the timeloop library
import time
from timeloop import Timeloop
from datetime import timedelta
tl = Timeloop()
@tl.job(interval=timedelta(seconds=2))
def sample_job_every_2s():
print("2s job current time : {}".format(time.ctime()))
if __name__ == "__main__":
tl.start(block=True)These eight approaches cover a wide range of scenarios for implementing scheduled tasks in Python.
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.