首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python HTTPServer和周期性任务

Python HTTPServer和周期性任务
EN

Stack Overflow用户
提问于 2020-11-12 19:26:01
回答 1查看 165关注 0票数 1

我正在使用HTTPServer来监听传入的POST请求并为它们提供服务。所有的工作都很好。

我需要在脚本中添加一些周期性任务(每X秒:做一些事情)。因为HTTP服务器在以下情况下接受完整命令

代码语言:javascript
复制
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()的检查包含在以下内容中:

代码语言:javascript
复制
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

欢迎任何想法。谢谢!

EN

回答 1

Stack Overflow用户

发布于 2020-11-12 21:54:49

感谢@rdas为我提供了单独的线程解决方案。我尝试过schedule,但它不能与超文本传输协议服务器一起工作,因为我无法告诉脚本运行挂起的作业。

我尝试使用threading,以守护进程的身份运行定期任务。它成功了!代码结构如下:

代码语言:javascript
复制
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服务器不会阻塞线程,所以它工作得很好。

顺便说一句,我正在使用文件“触摸”作为这个过程的生命证明。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64803011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档