Gracefully finish background tasks on shutdown
このコミットが含まれているのは:
コミット
236d73a342
|
@ -58,11 +58,13 @@ def create_app():
|
||||||
app.users = app.users_by_token.values()
|
app.users = app.users_by_token.values()
|
||||||
app.segments_directory_cache = DirectoryCache(config['stream']['segments_dir'])
|
app.segments_directory_cache = DirectoryCache(config['stream']['segments_dir'])
|
||||||
|
|
||||||
@app.while_serving
|
app.background_sleep = set()
|
||||||
|
|
||||||
|
@app.after_serving
|
||||||
async def shutdown():
|
async def shutdown():
|
||||||
app.shutting_down = False
|
# make all background tasks finish
|
||||||
yield
|
for task in app.background_sleep:
|
||||||
app.shutting_down = True
|
task.cancel()
|
||||||
|
|
||||||
@app.before_serving
|
@app.before_serving
|
||||||
async def startup():
|
async def startup():
|
||||||
|
|
|
@ -12,17 +12,25 @@ MESSAGES = current_app.messages
|
||||||
USERS_BY_TOKEN = current_app.users_by_token
|
USERS_BY_TOKEN = current_app.users_by_token
|
||||||
USERS = current_app.users
|
USERS = current_app.users
|
||||||
|
|
||||||
|
async def sleep_and_collect_task(delay):
|
||||||
|
coro = asyncio.sleep(delay)
|
||||||
|
task = asyncio.create_task(coro)
|
||||||
|
current_app.background_sleep.add(task)
|
||||||
|
try:
|
||||||
|
await task
|
||||||
|
finally:
|
||||||
|
current_app.background_sleep.remove(task)
|
||||||
|
|
||||||
def with_period(period):
|
def with_period(period):
|
||||||
def periodically(f):
|
def periodically(f):
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
async def wrapper(*args, **kwargs):
|
async def wrapper(*args, **kwargs):
|
||||||
await asyncio.sleep(period)
|
|
||||||
while True:
|
while True:
|
||||||
if current_app.shutting_down:
|
try:
|
||||||
|
await sleep_and_collect_task(period)
|
||||||
|
except asyncio.CancelledError:
|
||||||
break
|
break
|
||||||
else:
|
|
||||||
f(*args, **kwargs)
|
f(*args, **kwargs)
|
||||||
await asyncio.sleep(period)
|
|
||||||
|
|
||||||
return wrapper
|
return wrapper
|
||||||
|
|
||||||
|
|
読み込み中…
新しいイシューから参照