4.20 Python实现定时任务的多种方案及代码示例

目录

前言

  • Python定时任务是指在程序运行过程中,周期性地执行一些特定的任务,比如每天定时执行某个函数或者脚本等。它可以免去手动重复执行某些操作的繁琐,提高工作效率和准确性。
  • Python定时任务的原理是基于计划任务(Cron Job)或调度器来实现的。计划任务是一种在Linux系统下常见的定时任务管理方式,而调度器则是Python中实现定时任务的一种方式。调度器的原理是通过创建一个线程来不断运行,并根据给定的时间间隔或时间点来执行指定的任务。
  • Python中有多个调度器可以使用,比如APScheduler、schedule等。这些调度器可以根据需求自由选择,支持复杂的定时任务设置,可以根据需要支持秒级别和微秒级别的任务调度。使用Python调度器可以极大地方便开发人员控制和调度程序的执行,从而提高工作效率。

一、12种方案及代码示例

1. 使用time.sleep()实现简单定时任务

import time

def timed_task():
    print("This is a timed task.")
    return

while True:
    # 定义任务执行间隔时间,单位为秒
    interval = 10
    # 执行任务
    timed_task()
    # 等待指定时间后再次执行任务
    time.sleep(interval)

2. 使用schedule库实现复杂定时任务

import schedule
import time

def timed_task():
    print("This is a timed task.")
    return

# 定义任务调度计划
schedule.every(10).seconds.do(timed_task)

while True:
    # 执行任务计划
    schedule.run_pending()
    # 暂停一秒钟
    time.sleep(1)

3. 使用APScheduler库实现复杂定时任务

from apscheduler.schedulers.blocking import BlockingScheduler

def timed_task():
    print("This is a timed task.")
    return

# 创建调度器对象
scheduler = BlockingScheduler()

# 添加任务并设置触发条件
scheduler.add_job(timed_task, 'interval', seconds=10)

# 启动调度器
scheduler.start()

4. 使用Threading.Timer实现简单定时任务

import threading

def timed_task():
    print("This is a timed task.")
    t = threading.Timer(10, timed_task)
    t.start()

# 启动定时任务
timed_task()

5. 使用Asyncio库实现异步定时任务

import asyncio

async def timed_task():
    print("This is a timed task.")
    await asyncio.sleep(10)

# 创建一个事件循环对象
loop = asyncio.get_event_loop()

# 添加任务到事件循环中
loop.create_task(timed_task())

# 启动事件循环
loop.run_forever()

6. 使用Celery库实现分布式定时任务

from celery import Celery

app = Celery('tasks', broker='pyamqp://guest@localhost//')

@app.task
def timed_task():
    print("This is a timed task.")

# 设置定时任务调度计划
app.conf.beat_schedule = {
    'timed-task': {
        'task': 'tasks.timed_task',
        'schedule': 10.0,
    },
}

# 启动定时任务
app.worker_main(['-B', '-l', 'info'])

7. 使用APScheduler库的BlockingScheduler类实现简单定时任务

from apscheduler.schedulers.blocking import BlockingScheduler

def timed_task():
    print("This is a timed task.")

# 创建调度器对象
scheduler = BlockingScheduler()

# 添加任务并设置触发条件
scheduler.add_job(timed_task, 'interval', seconds=10)

# 启动调度器
scheduler.start()

8. 使用APScheduler库的BackgroundScheduler类实现后台定时任务

from apscheduler.schedulers.background import BackgroundScheduler

def timed_task():
    print("This is a timed task.")

# 创建调度器对象
scheduler = BackgroundScheduler()

# 添加任务并设置触发条件
scheduler.add_job(timed_task, 'interval', seconds=10)

# 启动调度器
scheduler.start()

# 主线程继续执行其他任务
try:
    while True:
        pass
except KeyboardInterrupt:
    pass

# 关闭调度器
scheduler.shutdown()

9. 使用Cron表达式实现复杂定时任务

import schedule
import time

def timed_task():
    print("This is a timed task.")

# 定义任务调度计划,使用Cron表达式
schedule.every().day.at("09:30").do(timed_task)

while True:
    # 执行任务计划
    schedule.run_pending()
    # 暂停一秒钟
    time.sleep(1)

10. 使用apscheduler库的BackgroundScheduler类和BlockingScheduler类结合使用

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.blocking import BlockingScheduler

def timed_task():
    print("This is a timed task.")

# 创建后台调度器对象
background_scheduler = BackgroundScheduler()
# 创建阻塞调度器对象
blocking_scheduler = BlockingScheduler()

# 添加任务并设置触发条件
background_scheduler.add_job(timed_task, 'interval', seconds=10)

# 启动后台调度器
background_scheduler.start()

# 启动阻塞调度器(主线程将阻塞在这里)
blocking_scheduler.start()

11. 使用schedule库和多线程实现定时任务

import schedule
import threading
import time

def timed_task():
    print("This is a timed task.")

def run_schedule():
    while True:
        # 执行任务计划
        schedule.run_pending()
        # 暂停一秒钟
        time.sleep(1)

# 创建任务计划
schedule.every(10).seconds.do(timed_task)

# 创建并启动线程来执行任务计划
t = threading.Thread(target=run_schedule)
t.start()

12. 使用第三方库APScheduler和Flask结合实现定时任务Web接口

from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask

app = Flask(__name__)

def timed_task():
    print("This is a timed task.")

# 创建后台调度器对象
scheduler = BackgroundScheduler()

# 添加任务并设置触发条件
scheduler.add_job(timed_task, 'interval', seconds=10)

# 启动调度器
scheduler.start()

@app.route("/")
def hello():
    return "Hello, world!"

if __name__ == "__main__":
    app.run()

二、以上12种方案的使用场景及优缺点

  1. 使用time模块的sleep函数:适合简单的定时任务,不依赖第三方库,但在任务执行期间会阻塞主线程,可能影响其他任务的执行。
  2. 使用threading.Timer类:适合简单的定时任务,能够异步执行任务,使用方便,但在任务执行期间会阻塞子线程。
  3. 使用sched模块的scheduler类:适合在单线程环境下执行定时任务,可以设置精确的执行时间,但需要手动实现任务的调度和循环执行。
  4. 使用timeloop库:适合简单的定时任务,使用方便,能够异步执行任务,但功能相对较少,不支持复杂的定时策略。
  5. 使用schedule库:适合简单的定时任务,支持多种定时策略(间隔时间、指定时间),使用方便,但在任务执行期间会阻塞主线程。
  6. 使用APScheduler库的BlockingScheduler类:适合需要在定时任务执行期间阻塞主线程的场景,支持多种定时策略和任务触发条件,使用方便。
  7. 使用APScheduler库的BackgroundScheduler类:适合需要在后台执行定时任务的场景,不会阻塞主线程,支持多种定时策略和任务触发条件。
  8. 使用Cron表达式:适合复杂的定时任务,可以精确控制任务的执行时间和频率,但需要学习和理解Cron表达式的语法。
  9. 使用APScheduler库的BackgroundScheduler类和BlockingScheduler类结合使用:适合需要在后台执行定时任务,同时又需要阻塞主线程的场景。
  10. 使用schedule库和多线程实现定时任务:适合简单的定时任务,能够异步执行任务,使用方便。
  11. 使用第三方库APScheduler和Flask结合实现定时任务Web接口:适合将定时任务与Web应用结合,通过Web接口控制定时任务的启停和管理。

每种方案都有其适用的场景和优缺点,选择最合适的方案取决于任务的复杂度、并发性要求、是否需要阻塞主线程、是否与其他框架集成等因素。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ibun.song

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值