重启 Monitor 实例

Restarting a Monitor instance

我有一个 cherrypy 应用程序,它有一个像这样的 Monitor 实例:

        mail_checker = Monitor(cherrypy.engine, self.mail_processor.poll_history_feed, frequency=10)

简而言之,它会检查 gmail 收件箱中的新电子邮件并进行处理。有时 poll_history_feed() 会抛出异常,我现在猜测这是因为我们的互联网不稳定,并且它会停止 运行 直到我重新启动整个应用程序。 (下面的回溯样本)

    [01/Mar/2016:17:08:29] ENGINE Error in background task thread function <bound method MailProcessor.poll_history_feed of <mailservices.mailprocessor.MailProcessor object at 0x10a2f0250>>.
Traceback (most recent call last):
  File "/Users/hashtaginteractive/Projects/.venvs/emaild/lib/python2.7/site-packages/cherrypy/process/plugins.py", line 500, in run
    self.function(*self.args, **self.kwargs)
  File "/Users/hashtaginteractive/Projects/emaild/emaild-source/mailservices/mailprocessor.py", line 12, in poll_history_feed
    labelIds=["INBOX", "UNREAD"]
  File "/Users/hashtaginteractive/Projects/.venvs/emaild/lib/python2.7/site-packages/oauth2client/util.py", line 142, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/Users/hashtaginteractive/Projects/.venvs/emaild/lib/python2.7/site-packages/googleapiclient/http.py", line 730, in execute
    return self.postproc(resp, content)
  File "/Users/hashtaginteractive/Projects/.venvs/emaild/lib/python2.7/site-packages/googleapiclient/model.py", line 207, in response
    return self.deserialize(content)
  File "/Users/hashtaginteractive/Projects/.venvs/emaild/lib/python2.7/site-packages/googleapiclient/model.py", line 262, in deserialize
    content = content.decode('utf-8')
  File "/Users/hashtaginteractive/Projects/.venvs/emaild/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 23: invalid start byte

有什么方法可以设置它以便在发生异常时自动重启服务器或这个特定的 Monitor 实例吗?

为了方便起见,您必须将对 self.mail_processor.poll_history_feed 的调用包装在 try/except 块中并记录错误。

def safe_poll_history_feed(self):
    try:
        self.mail_processor.poll_history_feed()
    except Exception:
        cherrypy.engine.log("Exception in mailprocessor monitor", traceback=True)

然后使用safe_poll_history_feed方法