Python爬蟲(chóng)定時(shí)計(jì)劃任務(wù)的幾種常見(jiàn)方法

作 者:戰(zhàn)俘巡航
作者簡(jiǎn)介:爬蟲(chóng)工程師,具有豐富的分布式爬蟲(chóng)系統(tǒng)架構(gòu)和開(kāi)發(fā)經(jīng)驗(yàn),有APP安全、逆向等領(lǐng)域經(jīng)驗(yàn),現(xiàn)為菜J學(xué)Python核心技術(shù)團(tuán)隊(duì)成員之一。后臺(tái)回復(fù)“入群”,可拉你進(jìn)技術(shù)交流群。
點(diǎn)擊上方“Python爬蟲(chóng)與數(shù)據(jù)挖掘”,進(jìn)行關(guān)注
回復(fù)“書(shū)籍”即可獲贈(zèng)Python從入門到進(jìn)階共10本電子書(shū)
首先最容易的是while true死循環(huán)掛起,不廢話,直接上代碼:
import os
import time
import sys
from datetime import datetime, timedelta
def One_Plan():
# 設(shè)置啟動(dòng)周期
Second_update_time = 24 * 60 * 60
# 當(dāng)前時(shí)間
now_Time = datetime.now()
# 設(shè)置 任務(wù)啟動(dòng)時(shí)間
plan_Time = now_Time.replace(hour=9, minute=0, second=0, microsecond=0)
# 設(shè)置差值,-1 day, 21:48:53.246576,類似于這樣
# time.sleep()需要傳入int,所以下面使用.total_seconds()
# 主要用來(lái)計(jì)算差值,返回int,具體功能可以自行查閱相關(guān)資料
delta = plan_Time - now_Time
first_plan_Time = delta.total_seconds() % Second_update_time
print("距離第一次執(zhí)行需要睡眠%d秒" % first_plan_Time)
return first_plan_Time
# while Ture代碼塊,掛起程序,睡眠時(shí)間結(jié)束后調(diào)用函數(shù)名進(jìn)行執(zhí)行
while True:
s1 = One_Plan()
time.sleep(s1)
# 下面這里是自己定義的函數(shù),想跑代碼的可以換成hellow world函數(shù)或者注釋掉這行測(cè)試下
exe_file(D_list)
print("正在執(zhí)行首次更新程序")
from datetime import datetime
from threading import Timer
import time
# 定時(shí)任務(wù)
def task():
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
def timedTask():
'''
第一個(gè)參數(shù): 延遲多長(zhǎng)時(shí)間執(zhí)行任務(wù)(秒)
第二個(gè)參數(shù): 要執(zhí)行的函數(shù)
第三個(gè)參數(shù): 調(diào)用函數(shù)的參數(shù)(tuple)
'''
Timer(5, task, ()).start()
while True:
timedTask()
time.sleep(5)
7行代碼,是不是很優(yōu)雅??jī)?yōu)不優(yōu)雅的主要是代碼少,不費(fèi)勁對(duì)吧。
2020-06-05 14:06:39
2020-06-05 14:06:44
2020-06-05 14:06:49
2020-06-05 14:06:54
2020-06-05 14:06:59
2020-06-05 14:07:04
2020-06-05 14:07:09
2020-06-05 14:07:14
2020-06-05 14:07:19
2020-06-05 14:07:24
from datetime import datetime
import sched
import time
def timedTask():
# 初始化 sched 模塊的 scheduler 類,傳入(time.time, time.sleep)這兩個(gè)參數(shù)
scheduler = sched.scheduler(time.time, time.sleep)
# 增加調(diào)度任務(wù),enter(睡眠時(shí)間,執(zhí)行級(jí)別,執(zhí)行函數(shù))
scheduler.enter(5, 1, task)
# 運(yùn)行任務(wù)
scheduler.run()
# 定時(shí)任務(wù)
def task():
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
if __name__ == '__main__':
timedTask()
import schedule
import time
def hellow():
print('hellow')
def Timer():
schedule.every().day.at("09:00").do(hellow)
schedule.every().day.at("18:00").do(hellow)
while True:
schedule.run_pending()
time.sleep('需要睡眠的周期')
Timer()

在這里可以看到,有day-hour-minute,定時(shí)任務(wù)非常的方便,在while True里添加需要睡眠的時(shí)間,在函數(shù)模塊內(nèi)添加需要執(zhí)行的次數(shù)即可。
------------------- End -------------------
往期精彩文章推薦:
手把手教你使用Python輕松搞定發(fā)郵件
手把手教你用Python制作簡(jiǎn)易小說(shuō)閱讀器
一篇文章總結(jié)一下Python庫(kù)中關(guān)于時(shí)間的常見(jiàn)操作

歡迎大家點(diǎn)贊,留言,轉(zhuǎn)發(fā),轉(zhuǎn)載,感謝大家的相伴與支持
想加入Python學(xué)習(xí)群請(qǐng)?jiān)诤笈_(tái)回復(fù)【入群】
萬(wàn)水千山總是情,點(diǎn)個(gè)【在看】行不行
/今日留言主題/
隨便說(shuō)一兩句吧~~
評(píng)論
圖片
表情
