如果你希望自开发一个轻量级的 Python 包来实现定时任务,而不依赖 Celery 等复杂框架,可以使用原生的 Python 工具如 threading
或 schedule
。以下是一个简单实现的方案。
threading
启动一个守护线程。my_simple_scheduler/
├── my_simple_scheduler/
│ ├── __init__.py
│ ├── scheduler.py
│ └── tasks.py
├── setup.py
└── README.md
__init__.py
用于初始化任务调度器,并在导入时启动。
from .scheduler import Scheduler
# Initialize and start the scheduler when the package is imported
scheduler = Scheduler()
scheduler.start()
scheduler.py
调度器的实现,负责启动守护线程并调度任务。
import threading
import time
from .tasks import my_task # 引用你定义的任务
class Scheduler:
def __init__(self):
self._stop_event = threading.Event()
self._thread = None
def _schedule_loop(self):
"""核心调度循环,每分钟执行一次任务"""
while not self._stop_event.is_set():
try:
my_task() # 调用你的任务
except Exception as e:
print(f"Error in scheduled task: {e}")
time.sleep(60) # 每隔 60 秒执行一次任务
def start(self):
"""启动调度器"""
if self._thread is None or not self._thread.is_alive():
self._stop_event.clear()
self._thread = threading.Thread(target=self._schedule_loop, daemon=True)
self._thread.start()
print("Scheduler started.")
def stop(self):
"""停止调度器"""
self._stop_event.set()
if self._thread:
self._thread.join()
print("Scheduler stopped.")
tasks.py
这里定义你的任务逻辑,可以添加多个任务。
def my_task():
"""定时执行的任务"""
print("Executing scheduled task...")
# 在这里实现你的任务逻辑
with open("task_log.txt", "a") as f:
f.write("Task executed at: " + time.strftime("%Y-%m-%d %H:%M:%S") + "\n")
setup.py
用于发布和安装你的包。
from setuptools import setup, find_packages
setup(
name='my_simple_scheduler',
version='0.1.0',
description='A lightweight scheduler for periodic tasks.',
author='Your Name',
packages=find_packages(),
install_requires=[],
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
],
)
安装你的包
pip install .
运行你的包
在任何 Python 脚本中引入后,调度器会自动启动:
import my_simple_scheduler
# 你的主程序逻辑
print("Main program running...")
time.sleep(300) # 等待 5 分钟,观察调度器是否每分钟执行任务
手动停止调度器
如果需要显式停止调度器,可以调用:
my_simple_scheduler.scheduler.stop()
修改 scheduler.py
支持任务列表:
class Scheduler:
def __init__(self):
self._stop_event = threading.Event()
self._thread = None
self.tasks = []
def add_task(self, task):
"""动态添加任务"""
self.tasks.append(task)
def _schedule_loop(self):
while not self._stop_event.is_set():
for task in self.tasks:
try:
task()
except Exception as e:
print(f"Error in task {task.__name__}: {e}")
time.sleep(60)
使用时:
from my_simple_scheduler.scheduler import Scheduler
scheduler = Scheduler()
scheduler.add_task(my_task)
scheduler.add_task(another_task) # 添加另一个任务
scheduler.start()
支持不同任务有不同的调度间隔:
class Scheduler:
def __init__(self):
self.tasks = []
def add_task(self, task, interval):
"""添加任务及其间隔"""
self.tasks.append((task, interval, time.time()))
def _schedule_loop(self):
while not self._stop_event.is_set():
current_time = time.time()
for task, interval, last_run in self.tasks:
if current_time - last_run >= interval:
try:
task()
except Exception as e:
print(f"Error in task {task.__name__}: {e}")
self.tasks = [
(t, i, current_time if t == task else lr)
for t, i, lr in self.tasks
]
time.sleep(1)
守护线程
daemon=True
,确保主线程退出时子线程不会阻塞。任务执行时间
异常处理
轻量应用
这样设计可以轻量、灵活地实现一个无外部依赖的定时任务包,非常适合单一用途的小型项目。