When you have some blocking task that doesn't play nice with the async event loop, you have to put it in a separate thread.
If you're going to have an unbounded number of blocking tasks, you want to use a thread pool.
Either way, you want to have a wrapper async task that blocks on notification from the threaded task.
The easiest way to do this is to use a pre-built library like tornado-threadpool.* Then, you just do something like this:
class LongHandler(tornado.web.RequestHandler):
@thread_pool.in_thread_pool
def long_time_function(self, callback):
time.sleep(5)
callback("foo")
If you want to do it yourself, this gist shows an example of what you have to do—or, of course, the source code for the various Tornado threadpool libraries can serve as sample code.
Just keep in mind the limitations of the Python GIL: If your background task is CPU-bound (and does most of the work in Python, rather than in a C extension that releases the GIL like numpy), you have to put it in a separate process. A quick search for Tornado process pool libraries didn't turn up as many nice options, but adapting thread pool code to process pool code is usually very easy in Python.**
* Note that I'm not specifically recommending that library; it's just the first thing that came up in a Google search, and it looks usable and correct from a quick glance.
** It's often as simple as replacing concurrent.futures.ThreadPoolExecutor with concurrent.futures.ProcessPoolExecutor or multiprocessing.dummy.Pool with multiprocessing.Pool. The only trick is to make sure that all of your task arguments and return values are small and pickleable.