當你需要在 Python 中定期執(zhí)行任務(wù)時,schedule
庫是一個非常實用的工具。它可以幫助你自動化定時任務(wù)。以下是一些使用示例:
-
基本使用:
import schedule import time def job(): print("I'm working...") schedule.every(10).minutes.do(job) while True: schedule.run_pending() time.sleep(1)
上面的代碼表示每隔 10 分鐘執(zhí)行一次
job
函數(shù),非常簡單方便。 -
更多調(diào)度任務(wù)例子:
import schedule import time def job(): print("I'm working...") # 每十分鐘執(zhí)行任務(wù) schedule.every(10).minutes.do(job) # 每個小時執(zhí)行任務(wù) schedule.every().hour.do(job) # 每天的10:30執(zhí)行任務(wù) schedule.every().day.at("10:30").do(job) # 每個月執(zhí)行任務(wù) schedule.every().monday.do(job) # 每個星期三的13:15分執(zhí)行任務(wù) schedule.every().wednesday.at("13:15").do(job) # 每分鐘的第17秒執(zhí)行任務(wù) schedule.every().minute.at(":17").do(job) while True: schedule.run_pending() time.sleep(1)
-
只運行一次任務(wù):
import schedule import time def job_that_executes_once(): # 此處編寫的任務(wù)只會執(zhí)行一次... return schedule.CancelJob schedule.every().day.at('22:30').do(job_that_executes_once) while True: schedule.run_pending() time.sleep(1)
-
參數(shù)傳遞給作業(yè):
import schedule def greet(name): print('Hello', name) # 將額外的參數(shù)傳遞給 job 函數(shù) schedule.every(2).seconds.do(greet, name='Alice') schedule.every(4).seconds.do(greet, name='Bob')
-
獲取目前所有的作業(yè):
all_jobs = schedule.get_jobs()
-
取消所有作業(yè):
schedule.clear()
-
標簽功能:
# 打標簽 schedule.every().day.do(greet, 'Andrea').tag('daily-tasks', 'friend') schedule.every().hour.do(greet, 'John').tag('hourly-tasks', 'friend') # 獲取所有該標簽的任務(wù) friends = schedule.get_jobs('friend') # 取消所有 daily-tasks 標簽的任務(wù) schedule.clear('daily-tasks')
-
設(shè)定作業(yè)截止時間:文章來源:http://www.zghlxwxcb.cn/news/detail-831894.html
from datetime import datetime, timedelta, time def job(): print('Boo') # 每個小時運行作業(yè),18:30后停止 schedule.every(1).hours.until("18:30").do(job) # 其他截止時間設(shè)置...
[這些示例涵蓋了從秒到月的不同配置,你可以根據(jù)需求選擇合適的定時任務(wù)方式。文章來源地址http://www.zghlxwxcb.cn/news/detail-831894.html
到了這里,關(guān)于python自動定時任務(wù)schedule庫的使用方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!