python如何定时执行

原创
ithorizon 7个月前 (09-30) 阅读数 53 #Python

Python定时执行任务的方法

Python提供了多种方式来定时执行任务,以下是一些常见的方法:

1、使用time模块

Python的time模块可以帮助我们实现定时执行任务,time.sleep()函数可以让程序暂停执行一段时间,以下是一个简单的示例:

import time
print("开始执行任务")
time.sleep(5)  # 等待5秒钟
print("任务执行完毕")

2、使用schedule模块

schedule模块可以帮助我们按照指定的时间间隔定时执行任务,以下是一个简单的示例:

import schedule
import time
def job():
    print("执行任务")
schedule.every(10).seconds.do(job)  # 每10秒执行一次任务
while True:
    schedule.run_pending()  # 运行已到期的任务
    time.sleep(1)  # 等待1秒钟

3、使用threading模块

如果需要在后台执行定时任务,可以使用threading模块,以下是一个简单的示例:

import threading
import time
def job():
    print("执行任务")
    threading.Timer(10.0, job).start()  # 每10秒执行一次任务
thread = threading.Thread(target=job)
thread.start()  # 启动线程

是Python常见的三种定时执行任务的方法,你可以根据自己的需求选择其中的一种。



热门