How do I start/stop Hypercorn/Uvicorn server as a background task for an async application (like a discord bot) Python

I am currently creating a django application w/ asgi and I am currently having problems of setting up hypercorn and uvicorn to run in background with graceful shutdown. When I set up my application from asgi to run on hypercorn only using asyncio.create_task and starting it only, the website doesn't run.

Hypercorn code snippet:

from scripts import funcs
import nextcord
from nextcord.ext import commands
from nextcord import Interaction
import asyncio
# from uvicorn import Config, Server
# import uvicorn
import subprocess
from subprocess import CREATE_NEW_CONSOLE
import signal
# import multiprocessing
import nest_asyncio
import os
import sys
sys.path.insert(1, 'C:\\Users\\Sub01\\Project\\PaulWebsite\\app')
from hypercorn.config import Config
from hypercorn.asyncio import serve
from import run
import hypercorn
import asyncio
from paul_site.asgi import application
import signal

createEmbed = funcs.embedCreator()

shutdown_event = asyncio.Event()

def _signal_handler(*_) -> None:

    config = Config()
    coro = None
    def __init__(self) -> None:
        self.evtLoop = asyncio.new_event_loop()
    async def start(self):
        self.coro = self.evtLoop.create_task(await serve(application, self.config))

    def stop(self):
        self.evtLoop.add_signal_handler(signal.SIGINT, _signal_handler)
            asyncio.to_thread(serve(application, self.config, shutdown_trigger=shutdown_event.wait))

class baseCommand(commands.Cog):
    proc = None

    def __init__(self, client):
        self.client = client = HYPERCORN()

    async def bot(self, interaction: Interaction):
    @bot.subcommand(description="Stops the bot")
    async def shutdown(self, interaction: Interaction):
        await interaction.response.send_message(embed=createEmbed.createEmbed(title="Exit", description="Bot's down", footer=f"Requested by {}"))

    # Create command group site
    async def site(self, interaction: Interaction):
    @site.subcommand(description="Starts the website")
    async def start(self, interaction: Interaction):
            await interaction.response.send_message(embed=createEmbed.createEmbed(title="Start Website", description=f"""
                                                                                  **Website started successfully**
                                                                                  """, footer=f"Requested by {}"))
        except Exception as e:
            await interaction.response.send_message(
                embed=createEmbed.createEmbed(title="Start Website Error", description=
                """, footer=f"Requested by {}")

    @site.subcommand(description='Stops the website')
    async def stop(self, interaction: Interaction):
        await interaction.followup.send(embed=createEmbed.createEmbed(title="Stop Website", description=f"""
                                                                              **Website stopped successfully!**
                                                                              """, footer=f"Requested by {}"))
        del self.proc

def setup(client):

Uvicorn code snippet:

import sys
sys.path.insert(1, 'C:\\Users\\Sub01\\Project\\PaulWebsite\\app')
import asyncio
from paul_site.asgi import application
import signal
import time
import uvicorn
from multiprocessing import Process

class UvicornServer(uvicorn.Server):
    def __init__(self, host: str = "", port: int = 8000): = host
        self.port = port
    async def setup(self):
        self.proc = Process(
                'port': self.port,
        await self.proc.start()
        await asyncio.sleep(0.5)
    async def down(self):

def blockingFunc():
    prevTime = time.time()
    while True:
        print("Elapsed time: ", time.time() - prevTime)
        if time.time() - prevTime >= 4:

async def main():
    server = UvicornServer()
    await server.setup()
    await server.down()

ASGI config for paul_site project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see

import os

from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application

from paul_site_app.ws_urlpatterns import ws_urlpatterns

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'paul_site.settings')

application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket': URLRouter(ws_urlpatterns)

Looking at the examples from people incorporating FastAPI and running uvicorn as a background task, I tried it but it only results in a runtime error. I've also tried having a command open a terminal and running the application via cli but soon realized that the code that invokes a new terminal isn't compatible with different platforms.

Back to Top