繁体   English   中英

Python HTTPServer 和周期性任务

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM