背景:
有一個爬蟲服務,需要定時從公開網站上拉取一些數據,為了避免被識別為爬蟲(防爬蟲的識別需要根據很多特征,時間僅僅是其中一個維度),需要在指定的時間內,隨機生成一個時間爬取
腳本是python寫的,直接上代碼...
import logging
import traceback
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()
def spider_schedule():
# spider_schedule是job_id
scheduler.remove_job('spider_schedule')
try:
print 'spider start... ', datetime.now().strftime('%Y-%m-%d %X')
#--------自己的業務代碼-------
pass
#---------------------------
print 'spider end... ', datetime.now().strftime('%Y-%m-%d %X')
except Exception as e:
print traceback.format_exc(e)
finally:
interval_minutes = random.randint(60, 120) # 1-120分鐘隨機選一個時間
interval_seconds = random.randint(1, 60) # 1~60秒隨機選一個時間
scheduler.add_job(spider_schedule, 'interval', minutes=interval_minutes, seconds=interval_seconds, id='spider_schedule')
if __name__ == '__main__':
scheduler.add_job(spider_schedule, 'interval', seconds=10, id='spider_schedule')
scheduler.start()
ps:下面看下python定時執行任務的三種方式
#!/user/bin/env python
# @Time :2018/6/7 16:31
# @Author :PGIDYSQ
#@File :PerformTaskTimer.py
#定時執行任務命令
#1.定時任務代碼
import time,os,sched
# schedule = sched.scheduler(time.time,time.sleep)
# def perform_command(cmd,inc):
# os.system(cmd)
# print('task')
# def timming_exe(cmd,inc=60):
# schedule.enter(inc,0,perform_command,(cmd,inc))
# schedule.run()
# print('show time after 2 seconds:')
# timming_exe('echo %time%',2)
#2.周期性執行任務
schedule = sched.scheduler(time.time,time.sleep)
def perform_command(cmd,inc):
#在inc秒后再次運行自己,即周期運行
schedule.enter(inc, 0, perform_command, (cmd, inc))
os.system(cmd)
def timming_exe(cmd,inc=60):
schedule.enter(inc,0,perform_command,(cmd,inc))
schedule.run()#持續運行,直到計劃時間隊列變成空為止
print('show time after 2 seconds:')
timming_exe('echo %time%',2)
#3.循環執行命令
# import time,os
# def re_exe(cmd,inc = 60):
# while True:
# os.system(cmd)
# time.sleep(inc)
# re_exe("echo %time%",5)
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

