我有一个程序,我需要活动(运行)大约一个星期。
该程序侦听网站的Feed,并根据收到的每个信号决定做什么。但是,我注意到程序暂停(在运行大约8小时后停止没有错误或标志)并且直到ctrl + c并重新启动才会恢复。鉴于python脚本可以运行的时间没有限制,我如何确保我的程序重新启动,比如每五个小时重启一次,这样我可以确保它不会停止工作?
我的程序使用import requests
及其类连接到REST API提要。
以下是侦听Feed的程序的一部分。
def connect():
domain = 'x'
access_token = 'x'
account_id = 'x'
instruments = 'x'
try:
# Tries to connect, if unsuccessful it will close the connection.
s = requests.Session()
url = "https://" + domain + "/v1/prices"
headers = {'Authorization': 'Bearer ' + access_token, }
params = {'instruments': instruments, 'accountId' : account_id}
req = requests.Request('GET', url, headers=headers, params=params)
pre = req.prepare()
resp = s.send(pre, stream=True, verify=True)
return resp
except Exception as e:
s.close()
print "Caught exception when connecting to stream\n" + str(e)
def demo(display_heartbeat):
response = connect()
if response.status_code != 200:
print response.text
return
for line in response.iter_lines(1):
if line:
try:
msg = json.loads(line)
except Exception as e:
print "Caught exception when converting message into json\n" + str(e)
return
if display_heartbeat:
print line
else:
if msg.has_key("instrument") or msg.has_key("tick"):
parser.json_parser(msg)
def main():
usage = "usage: %prog [options]"
parser = OptionParser(usage)
parser.add_option("-b", "--displayHeartBeat", dest="verbose", action="store_true",
help="Display HeartBeat in streaming data")
display_heartbeat = False
(options, args) = parser.parse_args()
if len(args) > 1:
parser.error("incorrect number of arguments")
if options.verbose:
display_heartbeat = True
demo(display_heartbeat)
if __name__ == "__main__":
main()