Python中常用的定时任务开发库是APScheduler,可以通过pip安装:pip install apscheduler
```python
from apscheduler.schedulers.background import BackgroundScheduler
def job():
print("定时任务执行")
# 创建调度器
scheduler = BackgroundScheduler()
# 添加定时任务,每隔5秒执行一次
scheduler.add_job(job, 'interval', seconds=5)
# 启动调度器
scheduler.start()
# 程序不退出,等待定时任务执行
while True:
pass
```
另一种实现定时任务的方法是使用crontab,通过在系统中设置定时任务来执行Python脚本。
首先编辑crontab配置文件:
crontab -e
然后添加一行定时任务,格式如下:
* * * * * python /path/to/your/script.py
以上配置表示每分钟执行一次指定的Python脚本。
最后保存并退出即可。
通过APScheduler库或者crontab可以很方便地实现Python定时任务的开发,开发者可以根据自己的需求选择合适的方法来实现定时任务。