[英]Python HTTPServer and periodic tasks
我使用 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 服務器不會阻塞線程,因此運行良好。
順便說一句,我使用文件“touching”作為該過程的生命證明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.