首页 >>  正文

python做定时任务

来源:baiyundou.net   日期:2024-09-22

作者:王忘杰

全民制作人大家好,我是学习python两天半的练习生王忘杰,喜欢路由交换、linux、网络安全,开整!这是我的第二篇0基础python文章,请大家支持,谢谢~

开发思路
用于监控指定的URL,在我的场景中,我是从腾讯VPS上监控公司宽带出口,当URL访问超时时,即为宽带故障。
设计思路很简单,访问失败发送告警,访问成功发送恢复通知,同时要使用配置文件进行配置,防止持续重复告警。

绘制开发流程图


使用python语言实现

#!/usr/bin/python3import requests
import time
import json
import os# 监测URL是否正常响应def url_check(url):    # 当前时间    check_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
   try:        # 请求URL, 设置3s超时, 忽略SSL证书        r = requests.get(url, timeout=3, verify=False)
       if r.status_code == 200:
           fo = open(config,"r")
           line = fo.read(1)
           print(line)            #判断配置文件内容            if line == "1":
               print("发送报警")
               fo.close()
               fo = open(config, "w")
               fo.write('0')
               print("配置重置为0")                # 请求响应状态                msg = "监控的URL:%s%sURL恢复状态正常:%s%s监测时间:%s" % (
               url, "nn", r.status_code, "nn", check_time)                # 推送消息                yun_push(msg)
           else:
               print("当前配置为",line)
               fo = open(config, "w")
               fo.write('0')
               print("配置重置为0")
       else:
           fo = open(config, "r")
           line = fo.read(1)
           print(line)
           if line == "1":
               print("退出程序")
           else:
               print("发送报警")
               fo.close()
               fo = open(config, "w")
               fo.write('1')
               print("配置重置为1")                # 请求响应状态                msg = "监控的URL:%s%sURL访问异常:%s%s监测时间:%s" % (
                   url, "nn", r.status_code, "nn", check_time)                # 推送消息                yun_push(msg)
   except:
       fo = open(config, "r")
       line = fo.read(1)
       print(line)
       if line == "1":
           print("退出程序")
       else:
           print("发送报警")
           fo.close()
           fo = open(config, "w")
           fo.write('1')
           print("配置重置为1")            # 请求响应状态            msg = "监控的URL:%s%sURL访问失败,无法连接%s监测时间:%s" % (
               url, "nn", "nn", check_time)            # 推送消息            yun_push(msg)

def yun_push(content):
   url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=用自己的'
   s = json.dumps({'msgtype': 'text', 'text': {"content" : content}})
   print(requests.post(url, data=s).text)

if __name__ == '__main__':    #判断配置文件是否存在,不存在则生成配置文件并退出,配置文件则存在执行    config = './baidu.config'
   if not os.path.exists(config):
       print("配置文件不存在")
       file = open(config,'w')
       file.close()
       print("配置文件已生成")
   else:
       print("配置文件存在,执行URL检测")
       url_check("https://www.baidu.com/")

运行效果


正式使用
在VPS部署python脚本,并设置定时任务即可


查看文章精彩评论,请前往什么值得买进行阅读互动

","gnid":"96c6a833d821e0468","img_data":[{"flag":2,"img":[{"desc":"","height":"274","title":"","url":"https://p0.ssl.img.360kuai.com/t015394727360c3cdc6.jpg","width":"600"},{"desc":"","height":"616","title":"","url":"https://p0.ssl.img.360kuai.com/t016ff92dc7f2116c3c.jpg","width":"359"}]}],"original":0,"pat":"art_src_1,fts0,sts0","powerby":"hbase","pub_time":1683810195000,"pure":"","rawurl":"http://zm.news.so.com/41b69145e2771cb08cd67bac9f05abc6","redirect":0,"rptid":"4cdf902d8b0d23e5","rss_ext":[],"s":"t","src":"什么值得买","tag":[{"clk":"ktechnology_1:机器人","k":"机器人","u":""}],"title":"0基础上手python编程,实践URL监控+企业微信机器人告警

尉秦娜3288python 怎么定时每天在凌晨2点 输出hello word 也就是到时间执行print he -
辕兔周19846615528 ______ 定时执行一般需要符合以下条件 使用cron之类的计划任务程序来调用 程序在后台循环执行 后台循环一般代码:import time while True: current_time = time.localtime(time.time()) if((current_time.tm_hour == 2) and (current_time.tmin == 0) and (current_time.tsec == 0)): print "Hello World" time.sleep(1)

尉秦娜3288如何用python做简单的定时关机软件 -
辕兔周19846615528 ______ import os from time import sleep import arrow endTime = '15:45' m,s = endTime.split(":") while 1: if arrow.houre = = m and arrow.second ==s: os.system('shutdown -s -t 0) sleep(0.2)

尉秦娜3288Python需要定时任务,时间是不固定的.需要处理的任务也不固定,怎么捉. -
辕兔周19846615528 ______ 开个子线程,里面放下面的代码 while True:dosomethings()# 查询任务列表,执行任务列表 time.sleep(60) 也就是每分钟检查一次,注意这个查询是要放到 子线程 处理的.

尉秦娜3288python 定时循环执行命令,时间判断如何写? -
辕兔周19846615528 ______ str和int比较当然不行喽 t = time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time())) 转成这样再比较吧

尉秦娜3288python中如何定时执行某一个函数 -
辕兔周19846615528 ______ 建议用linux的crontab来设置

尉秦娜3288用python写脚本,定时发送http请求 -
辕兔周19846615528 ______ import httplib, urllib import datetime import time conn = httplib.HTTPConnection("xxx.com:80") headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} f = open("log.txt","w") for i in range(1,1001): ...

尉秦娜3288用python写脚本,定时发送http请求 -
辕兔周19846615528 ______ import httplib, urllib import datetime import time conn = httplib.HTTPConnection("xxx.com:80") headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} f = open("log.txt","w") for i in range(1,1001): ...

尉秦娜3288使用crontab,定时执行一个python脚本,怎么不能用 -
辕兔周19846615528 ______ 注意两点:1. crontab 不会有你设的环境变量2. crontab 要用绝对路径 正确做法写一个shell脚本,在脚本内设置环境变量及执行python语句,然后crontab执行该脚本.123 #/usr/bin/bash PATH=/home//Python-3.3.3:/home//Python-3.3.3/bin:$PATH python /home/xxx.py

尉秦娜3288linux定时任务怎么实现:延时执行任务,然后进入一个定时执行任务,最后将任务删除? -
辕兔周19846615528 ______ 提供个思路,先用at设定在3天后执行任务a,然后任务a里是将每8小时执行任务b的要求写入crondtab,任务b中设定先读取文件,看是否达到8次,达到了则删除自己,没有达到则执行任务在执行结束后写入某个文件来计数.说一下几个关键点,at可能需要安装,并且你要确定atd进程已经启动,并且这个设定at的功能也可以通过单独脚本实现 删除自己则可以使用rm -f $0 实现 写入crondtab可以根据用户和系统不同文件位置不同,如centos7的root用户在/var/spool/cron/root,修改该文件可以使用sed -i或者awk等实现.以上是bash脚本实现思路 如果写一个python当守护进程也可以实现过程类似.

尉秦娜3288python调用接口数据怎么设置定时器,没30分钟刷新一次 -
辕兔周19846615528 ______ # 1.简单的 time.sleep + while import time def test_api(): print("test_api_log") while True: test_api() time.sleep(60*30)# 2.时间调度模块 sched import time, os, sched # 第一个参数确定任务的时间,返回从某个特定的时间到现在经历的秒数 # 第二...

(编辑:自媒体)
关于我们 | 客户服务 | 服务条款 | 联系我们 | 免责声明 | 网站地图 @ 白云都 2024