温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Python怎么设置随机时间执行定时任务

发布时间:2021-04-19 18:03:29 来源:亿速云 阅读:999 作者:Leah 栏目:开发技术

使用Python怎么设置随机时间执行定时任务?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

Python主要用来做什么

Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。

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定时执行任务的三种方式

#定时执行任务命令
#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怎么设置随机时间执行定时任务问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI