Reputation: 20126
What would be the easiest way of creating a Python server (XML-RPC Server) that shuts itself after sometime being idle?
I was thinking to do it like this but I don't know what to do in the todo's:
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()
I also tried to explore signal.alarm()
following the example here but it won't run under Windows throwing AttributeError: 'module' object has no attribute 'SIGALRM'
at me.
Thanks.
Upvotes: 1
Views: 408
Reputation: 34194
You can create your own server class that extends SimpleXMLRPCServer
in order to shutdown when idle for sometime.
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)
Now, you can use this class instead to make your server object.
# Create server
server = MyXMLRPCServer(("localhost", 7789))
server.register_introspection_functions()
Upvotes: 1