Skip to content

Instantly share code, notes, and snippets.

@pyk
Created January 19, 2018 09:55
Show Gist options
  • Save pyk/41cfd1f63db02490c50e241dc501eb92 to your computer and use it in GitHub Desktop.
Save pyk/41cfd1f63db02490c50e241dc501eb92 to your computer and use it in GitHub Desktop.
Sanic Fire & Forget
from sanic import Sanic
from sanic import response
import asyncio
api = Sanic(__name__)
@api.listener("before_server_start")
async def initialize_tasks_set(api, loop):
api.tasks = set()
async def busy_work(second):
await asyncio.sleep(second)
print("busy_work is DONE")
@api.get("/")
async def index(request):
await busy_work(10)
return response.json({"status": "ok"})
@api.get("/hello")
async def hello(request):
return response.json({"status": "ok"})
@api.get("/fire")
async def fire(request):
future = asyncio.ensure_future(busy_work(10))
api.tasks.add(future)
future.add_done_callback(api.tasks.remove)
return response.json({"status": "ok"})
@api.listener("after_server_stop")
async def wait_pending_busy_work(api, loop):
print("waiting busy work")
if len(api.tasks) > 0:
await asyncio.wait(api.tasks, loop=loop)
print("all busy work is done")
if __name__ == "__main__":
api.run(workers=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment