每隔X秒从用户输入一次运行python脚本

时间:2018-06-29 13:14:44

标签: python timer scheduled-tasks scheduling apscheduler

我有以下python代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import requests
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

#Function to get the health of the cluster
def getClusterHealth():
    try:
        response = requests.get('http://127.0.0.1:2379/health')
        data = response.json()
        if data['health']=="true":
            print("Cluster is healthy")
            getClusterMetrics()
        elif data['health']!="true":
            print ("Cluster is not healthy")
            sendEmail()
    except requests.exceptions.ConnectionError as e:
        print e
        print("Cluster is down")
        sendEmail()

#Function to get the netrics of the cluster
def getClusterMetrics():
    try:
        response = requests.get('http://127.0.0.1:2379/metrics')
        with open('clusterMetrics.txt','w') as f:
            f.write(response.text)
            f.close()
            print("Cluster Metrics saved in file: clusterMetrics.txt")
    except requests.exceptions.ConnectionError as e:
        print e
        sendEmail()

#Function to send emails in case of failures
def sendEmail():
    msg = MIMEText("etcd Cluster Down Sample Mail")
    sender = "etcd Cluster - 10.35.14.141"
    recipients = ["sample@email.com"]
    msg["Subject"] = "etcd Cluster Monitoring Test Multiple ID"
    msg['From'] = sender
    msg['To'] = ", ".join(recipients)
    s = smtplib.SMTP('localhost')
    s.sendmail(sender,recipients,msg.as_string())
    s.quit()

if __name__ == "__main__":

    if(len(sys.argv) < 2):
        print("Usage : python etcdMonitoring.py [health|metrics]")
    elif(sys.argv[1] == "health"):
        getClusterHealth()
    elif(sys.argv[1] == "metrics"):
        getClusterMetrics()

我想运行整个脚本X秒,作为用户输入的时间。但是,使用此输入,我想在函数中执行一些基于计时器的函数。它应该显示输出/做某些我想做的事情(此处不能显示代码),但是内部函数将针对用户给定的多个输入运行。例如,如果输入为30,则脚本应每30秒运行一次,但我应该能够每两分钟检查一次集群是否运行正常。

1 个答案:

答案 0 :(得分:1)

我前段时间遇到了这样的问题,只需将要每隔X秒执行的代码放入一个函数中,然后使用线程化python模块将其作为线程运行,但是不要忘记关闭线程在关闭程序之前使用thread.cancel()thread.exit()(使用atexit或自己的实现),因为如果不这样做,该函数将继续执行。

import atexit
import threading
X = input("Repeat code every ? sec")
def code(X):
  thread = threading.Timer(float(X), code)
  thread.start()
  '''
  your
  code
  '''
def exit():
  thread.cancel() #or thread.exit()
atexit.register(exit)

更多信息:
Run certain code every n seconds
How to close a thread from within?