Python 定时任务每天运行一次
在实际开发项目中,经常会遇到需要定时执行某个任务的场景,比如需要每天定时发送邮件、清理日志文件等。Python 提供了很多库来帮助我们实现定时任务,比如 schedule
、apscheduler
等。本文将以 schedule
库为例,详细介绍如何使用 Python 实现每天定时运行任务的功能。
1. 安装 schedule
库
首先我们需要安装 schedule
库,可以通过 pip 来安装:
pip install schedule
2. 编写定时任务函数
接下来我们需要编写一个函数,作为我们要定时执行的任务。比如我们编写一个简单的函数来输出当前的时间:
import datetime
def print_current_time():
current_time = datetime.datetime.now()
print(f"Current time is: {current_time}")
3. 使用 schedule
库设置定时任务
接下来我们使用 schedule
库来设置定时任务,具体的步骤如下:
- 导入相关库:
import schedule
import time
- 调用
schedule.every().day.at()
方法来设置每天的定时时间,然后调用job
方法来执行定时任务:
schedule.every().day.at("09:00").do(print_current_time)
- 在
while
循环中调用schedule.run_pending()
方法,使定时任务按照设定的时间执行:
while True:
schedule.run_pending()
time.sleep(1)
4. 完整代码示例
import datetime
import schedule
import time
def print_current_time():
current_time = datetime.datetime.now()
print(f"Current time is: {current_time}")
schedule.every().day.at("09:00").do(print_current_time)
while True:
schedule.run_pending()
time.sleep(1)
5. 运行结果
当你运行上述代码后,你会发现每天在早上 9 点,程序会输出当前的时间,如下所示:
Current time is: 2022-12-12 09:00:00.123456
6. 总结
通过以上几个步骤,我们成功实现了使用 Python 定时执行任务的功能。通过 schedule
库,我们可以方便地设置定时任务的执行时间,并且可以灵活地定制任务的执行逻辑。在实际项目中,你可以根据自己的需求来编写定时任务函数,并设置不同的执行时间,实现定时任务的自动化执行。