завершщение работы без убивания процесса

This commit is contained in:
Vladless
2024-10-21 02:08:47 +03:00
parent 456d9d4d3c
commit bc7594da66
8 changed files with 33 additions and 8 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+33 -8
View File
@@ -1,16 +1,14 @@
import asyncio
import logging
from aiogram.webhook.aiohttp_server import (SimpleRequestHandler,
setup_application)
import signal
from aiogram.webhook.aiohttp_server import (SimpleRequestHandler, setup_application)
from aiohttp import web
from bot import bot, dp, router
from config import WEBAPP_HOST, WEBAPP_PORT, WEBHOOK_PATH, WEBHOOK_URL
from database import init_db
from handlers.notifications import notify_expiring_keys
from handlers.pay import \
payment_webhook
from handlers.pay import payment_webhook
logging.basicConfig(level=logging.DEBUG)
@@ -26,6 +24,18 @@ async def on_startup(app):
async def on_shutdown(app):
await bot.delete_webhook()
for task in asyncio.all_tasks():
task.cancel()
try:
await asyncio.gather(*asyncio.all_tasks(), return_exceptions=True)
except Exception as e:
logging.error(f"Error during shutdown: {e}")
async def shutdown_site(site):
logging.info("Остановка сайта...")
await site.stop() # Остановка сайта
logging.info("Сервер остановлен.")
async def main():
dp.include_router(router)
@@ -44,8 +54,23 @@ async def main():
await site.start()
print(f"Webhook URL: {WEBHOOK_URL}")
await asyncio.Event().wait()
# Обработка сигналов завершения
loop = asyncio.get_event_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, lambda: asyncio.create_task(shutdown_site(site)))
try:
await asyncio.Event().wait() # Ожидание сигнала остановки
finally:
# Убедимся, что сессии закрыты и задачи завершены
pending = asyncio.all_tasks()
for task in pending:
task.cancel()
await asyncio.gather(*pending, return_exceptions=True)
if __name__ == '__main__':
asyncio.run(main())
try:
asyncio.run(main())
except Exception as e:
logging.error(f"Ошибка при запуске приложения: {e}")