Python定时任务随机时间执行的实现方法
作者:JouyPub 时间:2023-11-23 18:40:21
背景:
有一个爬虫服务,需要定时从公开网站上拉取一些数据,为了避免被识别为爬虫(防爬虫的识别需要根据很多特征,时间仅仅是其中一个维度),需要在指定的时间内,随机生成一个时间爬取
脚本是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)
来源:https://segmentfault.com/a/1190000020053471
标签:python,定时,任务
0
投稿
猜你喜欢
Python实现点云投影到平面显示
2021-05-10 14:51:15
python实现学生成绩测评系统
2023-08-09 19:40:56
pytorch_detach 切断网络反传方式
2022-09-25 21:10:50
Python基于随机采样一至性实现拟合椭圆(优化版)
2021-10-19 15:08:36
ASP显示当前在线人数统计代码
2010-04-24 15:47:00
浅谈flask源码之请求过程
2023-12-17 10:36:48
使用Python实现汉诺塔问题示例
2022-10-22 09:17:47
SQL Transcation的一些总结分享
2012-08-21 10:21:28
python 层次聚类算法图文示例
2023-09-25 05:57:46
利用python将 Matplotlib 可视化插入到 Excel表格中
2023-09-26 09:03:25
linux系统使用python监控apache服务器进程脚本分享
2021-10-15 00:15:41
两种oracle创建字段自增长的实现方式
2024-01-15 09:47:44
CentOS+Nginx+PHP+MySQL详细配置(图解)
2023-11-24 03:04:13
asp.net php asp jsp 301重定向的代码(集合)
2023-11-14 15:02:06
instanceof 内部机制探析
2009-09-25 13:09:00
oracle sys_connect_by_path 函数 结果集连接
2009-07-12 18:48:00
Python基础之getpass模块详细介绍
2021-03-06 13:47:13
Python 解析pymysql模块操作数据库的方法
2021-05-07 07:46:13
Python控制windows系统音量实现实例
2022-07-29 12:09:46
深入理解JS的事件绑定、事件流模型
2024-04-22 22:44:44