python实现轻量级的定时任务包,不引用celery等框架,在注册APP后自启动

如果你希望自开发一个轻量级的 Python 包来实现定时任务,而不依赖 Celery 等复杂框架,可以使用原生的 Python 工具如 threadingschedule。以下是一个简单实现的方案。


实现一个轻量级的定时任务包

核心功能
  1. 使用 threading 启动一个守护线程。
  2. 定时执行一个小任务,例如每分钟运行一次。
  3. 提供启动、停止功能。
  4. 避免复杂的依赖,纯 Python 实现。

项目结构

my_simple_scheduler/
    ├── my_simple_scheduler/
    │   ├── __init__.py
    │   ├── scheduler.py
    │   └── tasks.py
    ├── setup.py
    └── README.md

代码实现
1. __init__.py

用于初始化任务调度器,并在导入时启动。

from .scheduler import Scheduler

# Initialize and start the scheduler when the package is imported
scheduler = Scheduler()
scheduler.start()

2. 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.")

3. 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")

4. 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',
    ],
)

使用方式

  1. 安装你的包

    pip install .
    
  2. 运行你的包
    在任何 Python 脚本中引入后,调度器会自动启动:

    import my_simple_scheduler
    
    # 你的主程序逻辑
    print("Main program running...")
    time.sleep(300)  # 等待 5 分钟,观察调度器是否每分钟执行任务
    
  3. 手动停止调度器
    如果需要显式停止调度器,可以调用:

    my_simple_scheduler.scheduler.stop()
    

特性扩展(可选)

1. 支持多个任务

修改 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()

2. 动态调度间隔

支持不同任务有不同的调度间隔:

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)

注意事项

  1. 守护线程

    • 使用 daemon=True,确保主线程退出时子线程不会阻塞。
  2. 任务执行时间

    • 确保任务执行时间小于调度间隔(例如 60 秒),否则可能导致任务堆积。
  3. 异常处理

    • 捕获任务中的异常,避免整个调度线程崩溃。
  4. 轻量应用

    • 适用于小型定时任务。如果任务过于复杂或频繁运行,可以考虑引入专业工具(如 APScheduler)。

这样设计可以轻量、灵活地实现一个无外部依赖的定时任务包,非常适合单一用途的小型项目。

你可能感兴趣的:(python,开发语言,linux)