python 程序定时执行的实现

本文介绍如何使用Python的threading模块创建简单的定时器。通过定义不同的类实现倒计时功能,并在定时结束后执行指定操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面介绍以threading模块来实现定时器的方法。


使用前先做一个简单试验:

import threading
def sayhello():
        print "hello world"
        global t        #Notice: use global variable!
        t = threading.Timer(5.0, sayhello)
        t.start()

t = threading.Timer(5.0, sayhello)
t.start()

运行结果如下

>python hello.py
hello world
hello world
hello world

下面是定时器类的实现:

class Timer(threading.Thread):
        """
        very simple but useless timer.
        """
        def __init__(self, seconds):
                self.runTime = seconds
                threading.Thread.__init__(self)
        def run(self):
                time.sleep(self.runTime)
                print "Buzzzz!! Time's up!"

class CountDownTimer(Timer):
        """
        a timer that can counts down the seconds.
        """
        def run(self):
                counter = self.runTime
                for sec in range(self.runTime):
                        print counter
                        time.sleep(1.0)
                        counter -= 1
                print "Done"

class CountDownExec(CountDownTimer):
        """
        a timer that execute an action at the end of the timer run.
        """
        def __init__(self, seconds, action, args=[]):
                self.args = args
                self.action = action
                CountDownTimer.__init__(self, seconds)
        def run(self):
                CountDownTimer.run(self)
                self.action(self.args)

def myAction(args=[]):
        print "Performing my action with args:"
        print args
if __name__ == "__main__":
        t = CountDownExec(3, myAction, ["hello", "world"])
        t.start()


以下是Python实现定时任务的几种方法: 1. 使用while True和time.sleep()函数实现定时任务 ```python import time def some_task(): print("This is a timed task.") while True: some_task() time.sleep(60) # 每隔60秒执行一次任务 ``` 2. 使用threading.Timer定时器实现定时任务 ```python import threading def some_task(): print("This is a timed task.") def timer(): some_task() timer = threading.Timer(60, timer) # 每隔60秒执行一次任务 timer.start() timer() ``` 3. 使用Timeloop库实现定时任务 ```python from timeloop import Timeloop from datetime import timedelta tl = Timeloop() @tl.job(interval=timedelta(seconds=60)) def some_task(): print("This is a timed task.") tl.start(block=True) ``` 4. 使用调度模块sched实现定时任务 ```python import sched import time s = sched.scheduler(time.time, time.sleep) def some_task(): print("This is a timed task.") s.enter(60, 1, some_task, ()) # 每隔60秒执行一次任务 s.enter(60, 1, some_task, ()) s.run() ``` 5. 使用任务框架APScheduler实现定时任务 ```python from apscheduler.schedulers.blocking import BlockingScheduler def some_task(): print("This is a timed task.") scheduler = BlockingScheduler() scheduler.add_job(some_task, 'interval', seconds=60) # 每隔60秒执行一次任务 scheduler.start() ``` 6. 使用分布式消息系统celery执行定时任务 ```python from celery import Celery from datetime import timedelta app = Celery('tasks', broker='pyamqp://guest@localhost//') @app.task def some_task(): print("This is a timed task.") app.conf.beat_schedule = { 'some_task': { 'task': 'tasks.some_task', 'schedule': timedelta(seconds=60), # 每隔60秒执行一次任务 }, } app.conf.timezone = 'UTC' ``` 7. 使用Windows自带的定时任务 在Windows系统中,可以使用计划任务来实现定时任务。具体操作可以参考Windows系统的相关文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值