Python 定时任务

本文介绍了Python中实现定时任务的多种方式,包括`sched`模块、`threading.Timer`、`APScheduler`、`gevent`、`Twisted`、`Celery`和`Tornado`。每个框架都有其特点和适用场景,如`sched`适用于简单的延迟执行,`APScheduler`提供丰富调度类型,`Gevent`和`Tornado`基于事件驱动,`Celery`适合分布式任务调度。文章通过实例展示了如何使用这些工具进行定时任务设置。
摘要由CSDN通过智能技术生成

1. sched

https://docs.python.org/2/library/sched.html

作为一名Linux的SA,我们已经习惯了用crontab,而sched提供了一种延迟处理机制,也可以理解为任务调度的另一种方式的实现。

注意:

sched模块不是循环的,一次调度被执行后就Over了,如果想再执行,请再次enter

run()一直被阻塞,直到所有事件被全部执行完. 每个事件在同一线程中运行,所以如果一个事件的执行时间大于其他事件的延迟时间,那么,就会产生重叠。重叠的解决方法是推迟后来事件的执行时间。这样保证没有丢失任何事件,但这些事件的调用时刻会比原先设定的迟。

从3.3版本开始,scheduler是线程安全的。

举例:

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
    print "Doing stuff..."
    # do you stuff
    sc.enter(2, 1, do_something, (sc,))

s.enter(2, 1, do_something, (s,))
s.run()

2. threading.Timer

https://docs.python.org/2/library/threading.html?highlight=timer#timer-objects

Timer 不是循环的,一次调度被执行后就Over了,如果想再执行,请再次enter

举例:

#!/usr/bin/env python
from threading import Timer
from time import sleep

class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer = None
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.is_running = False
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值