python - Python HTTPServer 和周期性任务
问题描述
我正在使用 HTTPServer 来监听传入的 POST 请求并为它们提供服务。一切都很好。
我需要在脚本中添加一些周期性任务(每 X 秒:做一些事情)。由于 HTTP 服务器在之后执行完整命令
def run(server_class=HTTPServer, handler_class=S, port=9999):
server_address = (ethernetIP, port)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
我想是否有任何方法可以检查 time.time() 作为以下内容的一部分:
class S(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self._set_response()
self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))
def do_POST(self):
# my stuff here
欢迎任何想法。谢谢!
解决方案
感谢@rdas 将我指向单独的线程解决方案。我试过schedule
了,但它不适用于 HTTP 服务器,因为我无法告诉脚本运行挂起的作业。
我尝试使用threading
,将我的定期任务作为守护进程运行.. 它奏效了!下面是代码结构:
import time
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
polTime = 60 # how often we touch the file
polFile = "myfile.abc"
# this is the deamon thread
def polUpdate():
while True:
thisSecond = int(time.time())
if thisSecond % polTime == 0: # every X seconds
f = open(polFile,"w")
f.close() # touch and close
time.sleep(1) # avoid loopbacks
return "should never come this way"
# here´s the http server starter
def run(server_class=HTTPServer, handler_class=S, port=9999):
server_address = (ethernetIP, port)
httpd = server_class(server_address, handler_class)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
sys.exit(1)
# init the thread as deamon
d = threading.Thread(target=polUpdate, name='Daemon')
d.setDaemon(True)
d.start()
# runs the HTTP server
run(port=conf_port)
HTTP 服务器不会阻塞线程,所以它工作得很好。
顺便说一句,我正在使用“触摸”文件作为该过程的生命证明。
推荐阅读
- spring-boot - 无法通过 SpringBoot (docker) 应用程序连接到 kafka
- javascript - 如何用 1 个常数形成 3 的三进制
- android - 我需要对纬度和经度进行排序。离我现在的位置更近
- mysql - Freeradius 版本 2.2.8 sql 问题
- ios - 使用执行功能和 UI 更新重复动画
- validation - Yii2中form-group后如何设置errorPlacement
- php - 如何加载 PHP 页面,然后在保存之前检查它是否有错误?
- c++ - 为什么在对同一个字符数组使用 sizeof 时会得到不同的结果?
- android - 在 android studio 中读取文本文件
- android - Android 通知图像有时不显示