Search code examples
pythonloopstornado

Add game loop to tornado server in python


I've got a standard tornado application in python.

I am going to be making a game server using tornado's websockets.

The problem is, I need a game loop running on the server, to do things.

I could create a web handler '/startserver' and add the following code:

@tornado.web.asynchronous
def get(self):
    if not serverAlreadyStarted:
        serverAlreadyStarted = True
        while True:
            (...)

This feels very hackish, and it means every time I want to start to server, I need to go to /startserver

Is there a better way to do this? Is there somewhere when the server starts, I can add a loop?


Solution

  • You could just start it in the background like:

    @gen.coroutine
    def game_loop():
        while True:
            # Whatever your game loop does.
            print("tick")
            yield gen.sleep(1)
    
    if __name__ == "__main__":
        app = make_app()
        app.listen(8888)
        loop = tornado.ioloop.IOLoop.current()
        loop.spawn_callback(game_loop)
        loop.start()