Python定时任务随机时间执行的实现方法

yipeiwu_com5年前Python基础

背景:

有一个爬虫服务,需要定时从公开网站上拉取一些数据,为了避免被识别为爬虫(防爬虫的识别需要根据很多特征,时间仅仅是其中一个维度),需要在指定的时间内,随机生成一个时间爬取

脚本是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)

相关文章

在Python中用keys()方法返回字典键的教程

 keys()方法返回在字典中的所有可用的键的列表。 语法 以下是keys()方法的语法: dict.keys() 参数    ...

python调用百度REST API实现语音识别

目前,语音识别,即将语音内容转换为文字的技术已经比较成熟,遥想当时锤子发布会上展示的讯飞输入法语音识别,着实让讯飞火了一把。由于此类语音识别需要采集大量的样本,才能达到一定的准确度,个人...

python下载微信公众号相关文章

python下载微信公众号相关文章

本文实例为大家分享了python下载微信公众号相关文章的具体代码,供大家参考,具体内容如下 目的:从零开始学自动化测试公众号中下载“pytest"一系列文档 1、搜索微信号文章关键字搜索...

python模块导入的方法

模块在python编程中的地位举足轻重,熟练运用模块可以大大减少代码量,以最少的代码实现复杂的功能。 下面介绍一下在python编程中如何导入模块: (1)import 模块名:直接导入...

python3+PyQt5+Qt Designer实现堆叠窗口部件

python3+PyQt5+Qt Designer实现堆叠窗口部件

本文是对《Python Qt GUI快速编程》的第9章的堆叠窗口例子Vehicle Rental用Python3+PyQt5+Qt Designer进行改写。 第一部分无借用Qt De...