Add game loop to tornado server in python
<p>I've got a standard <code>tornado</code> application in <code>python</code>.</p>

<p>I am going to be making a game server using tornado's <code>websockets</code>.</p>

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

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

<pre><code>@tornado.web.asynchronous
def get(self):
    if not serverAlreadyStarted:
        serverAlreadyStarted = True
        while True:
            (...)
</code></pre>

<p>This feels very hackish, and it means <strong>every time</strong> I want to start to server, I need to go to <strong><code>/startserver</code></strong></p>

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

<p>You could just start it in the background like:</p>

<pre><code>@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()
</code></pre>

python loops tornado