日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python定時任務隨機時間執行的實現方法

系統 2640 0

背景:

有一個爬蟲服務,需要定時從公開網站上拉取一些數據,為了避免被識別為爬蟲(防爬蟲的識別需要根據很多特征,時間僅僅是其中一個維度),需要在指定的時間內,隨機生成一個時間爬取

腳本是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元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 酉阳| 五指山市| 永修县| 封开县| 永济市| 黑山县| 隆昌县| 营山县| 永春县| 二连浩特市| 昌乐县| 静安区| 南和县| 甘孜县| 五原县| 吉木萨尔县| 延庆县| 保山市| 阳高县| 甘孜县| 霍城县| 依兰县| 遂平县| 边坝县| 双辽市| 苏州市| 赤峰市| 泰来县| 临城县| 崇文区| 南投市| 会宁县| 洛南县| 华池县| 德格县| 长丰县| 兴城市| 肇州县| 吴旗县| 浏阳市| 靖江市|