微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python HTTPServer和定期任务

如何解决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服务器不会阻塞线程,因此效果很好。

顺便说一句,我正在使用文件“ touching”作为该过程的生命力证明。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。