我正在使用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欢迎任何想法。谢谢!
发布于 2020-11-12 21:54:49
感谢@rdas为我提供了单独的线程解决方案。我尝试过schedule,但它不能与超文本传输协议服务器一起工作,因为我无法告诉脚本运行挂起的作业。
我尝试使用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服务器不会阻塞线程,所以它工作得很好。
顺便说一句,我正在使用文件“触摸”作为这个过程的生命证明。
https://stackoverflow.com/questions/64803011
复制相似问题