在Python中实现定时任务,你可以使用以下几种方法:
1. 使用`time.sleep()`
import time
def task():
print("定时任务执行中...")
while True:
task()
time.sleep(60) 休眠1分钟
2. 使用`sched`模块
import sched
import time
s = sched.scheduler(time.time, time.sleep)
def task(sc):
print("定时任务执行中...")
s.enter(3600, 1, task, (sc,)) 安排任务在1小时后执行
s.run()
3. 使用`threading.Timer`
import threading
def task():
print("Task executed at", time.ctime())
如果需要重复执行,可以重新设置Timer
timer = threading.Timer(10, task)
timer.start()
4. 使用第三方库`schedule`
import schedule
import time
def job():
print("定时任务执行啦!")
每天早上8点执行
schedule.every().day.at("08:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)
5. 使用`APScheduler`
from apscheduler.schedulers.blocking import BlockingScheduler
def job():
print("执行任务")
每隔一小时执行
scheduler = BlockingScheduler()
scheduler.add_job(job, 'interval', hours=1)
scheduler.start()
Windows:使用任务计划程序
Linux:使用Cron
7. 使用Python脚本定时运行其他Python脚本
例如,在Windows任务计划程序中创建任务,或在Linux的Cron中设置定时任务来运行Python脚本。
选择适合你需求的方法来实现定时任务。