1

アイドル状態になると自動的にシャットダウンする Python サーバー (XML-RPC サーバー) を作成する最も簡単な方法は何でしょうか?

私はこのようにすることを考えていましたが、todo で何をすべきかわかりません:

from SimpleXMLRPCServer import SimpleXMLRPCServer

# my_paths variable
my_paths = []

# Create server
server = SimpleXMLRPCServer(("localhost", 7789))
server.register_introspection_functions()

# TODO: set the timeout
# TODO: set a function to be run on timeout

class MyFunctions:
    def add_path(paths):
        for path in paths:
            my_paths.append(path)
        return "done"

    def _dispatch(self, method, params):
        if method == 'add_path':
            # TODO: reset timeout
            return add_path(*params)
        else:
            raise 'bad method'

server.register_instance(MyFunctions())

# Run the server's main loop
server.serve_forever()

また、こちらsignal.alarm()の例に従って探索しようとしましたが、Windows では動作しません。AttributeError: 'module' object has no attribute 'SIGALRM'

ありがとう。

4

1 に答える 1

1

SimpleXMLRPCServerしばらくアイドル状態のときにシャットダウンするために拡張する独自のサーバー クラスを作成できます。

class MyXMLRPCServer(SimpleXMLRPCServer):
    def __init__(self, addr):
        self.idle_timeout = 5.0 # In seconds
        self.idle_timer = Timer(self.idle_timeout, self.shutdown)
        self.idle_timer.start()
        SimpleXMLRPCServer.__init__(self, addr)

    def process_request(self, request, client_address):
        # Cancel the previous timer and create a new timer
        self.idle_timer.cancel()
        self.idle_timer = Timer(self.idle_timeout, self.shutdown)
        self.idle_timer.start()
        SimpleXMLRPCServer.process_request(self, request, client_address)

これで、代わりにこのクラスを使用してサーバー オブジェクトを作成できます。

# Create server
server = MyXMLRPCServer(("localhost", 7789))
server.register_introspection_functions()
于 2012-10-08T14:22:52.743 に答える