python
复制代码
import asyncio
import time
from abc import ABC
from concurrent.futures import ProcessPoolExecutor
from tornado import web, ioloop, gen
async def async_task(name):
print(f"start: {name}")
st = int(time.time())
time.sleep(3) # 模拟同步等待
await asyncio.sleep(3) # 模拟异步等待
result = f"task: {name}, start: {st}, end: {int(time.time())}"
return result
def run_async_task(name):
return asyncio.run(async_task(name))
class MainHandler(web.RequestHandler, ABC):
executor = ProcessPoolExecutor() # 进程池
@gen.coroutine
def get(self):
task_name = self.get_argument("task", "task-1")
result = yield self.executor.submit(run_async_task, task_name)
self.write(result)
def make_app():
return web.Application([
(r"/", MainHandler),
])
if __name__ == '__main__':
app = make_app()
app.listen(8888)
print("http://localhost:8888/?task=task-X")
ioloop.IOLoop.current().start()