爬虫设置定时任务

用当前时间和设定的时间比较判断

import time
#
设置定时 def main(h, m): while True: now = datetime.datetime.now() #获取当前时间 print (now.hour, now.minute) #判断时间 if now.hour in h and now.minute in m: doSth() time.sleep(60) if __name__ =='__main__': main(h=[8,10,12,14,16,18,20], m=[0,30])

直接使用timer类

import time
import os
while 1:
    os.system("scrapy crawl News")

time.sleep(86400)

使用sched

import sched
# 初始化sched模块的scheduler类
# 第一个参数是一个可以返回时间戳的函数,第二个参数可以定时未到之前阻塞
schedule = sched.scheduler(time.time, time.sleep)

#被周期性调度出发的函数
def fun():
    os.system("scrapy crawl News")

def perform1(inc):
    schedule.enter(inc,0, perform1, (inc,))
    func()  # 需要周期执行函数

def mymain():
    schedule.enter(0,0, perform1, (86400))

if __name__ = "__main__":
    mymain()
    schedule.run() # 开始运行,直到计划时间队列变为空为止
 

使用Crontab实现Scrapy爬虫的定时执行

0 */24 * * * cd /data/spider && scrapy crawl article 

‘*/xx’等价于‘*’表示每xx小时执行一次

猜你喜欢

转载自www.cnblogs.com/wenm1128/p/11776895.html