如何設(shè)置Python爬蟲定時(shí)任務(wù)
首先最容易的是while true死循環(huán)掛起,不廢話,直接上代碼:
import?os
import?time
import?sys?
from?datetime?import?datetime,?timedelta
def?One_Plan():
?????#?設(shè)置啟動周期
?????Second_update_time?=?24?*?60?*?60
????#?當(dāng)前時(shí)間
????now_Time?=?datetime.now()
????#?設(shè)置?任務(wù)啟動時(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()?
????#?主要用來計(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ù)或者注釋掉這行測試下
????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ù):?延遲多長時(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)雅?優(yōu)不優(yōu)雅的主要是代碼少,不費(fèi)勁對吧。
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í)行級別,執(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ù)即可。

推薦閱讀
歡迎長按掃碼關(guān)注「數(shù)據(jù)管道」
評論
圖片
表情
