[英]Python HTTPServer and periodic tasks
I´m using HTTPServer to listen for incoming POST requests and serving them.我使用 HTTPServer 来监听传入的 POST 请求并为它们提供服务。 All is working fine with that.一切正常。
I need to add some periodic tasks in the script (every X seconds: do something).我需要在脚本中添加一些周期性任务(每 X 秒:做某事)。 As the HTTP server takes full command after由于 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()
I guess if there´s any way to include a check for time.time() as part of:我想是否有任何方法可以将 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
Any ideas are welcome.欢迎任何想法。 Thanks!谢谢!
Thanks to @rdas for pointing me to the separate thread solution.感谢@rdas 将我指向单独的线程解决方案。 I tried schedule
but it didn´t work with the HTTP server, because I can´t tell the script to run the pending jobs.我尝试了schedule
但它不适用于 HTTP 服务器,因为我无法告诉脚本运行挂起的作业。
I tried with threading
, running my periodic task as deamon.. and it worked: Here´s the code structure:我尝试使用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)
The HTTP server doesn´t block the thread, so it works great. HTTP 服务器不会阻塞线程,因此运行良好。
By the way, I´m using the file 'touching' as proof of life for the process.顺便说一句,我使用文件“touching”作为该过程的生命证明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.