I want restart gunicorn worker

Hi, I’m very junior developer, so I have some troble to handling errors.
My server using gunicorn 20.0.4 + sanic 19.12.2.

When I trying to connect to redis pool, most of case are fine, but once in a while, there are TimeoutError.
So, connection pool method return None Type. To avoid reference to None type, I decided to stop the server ( I mean gunicorn worker ). Then gunicorn make another worker instance.
But the issue of this code is when the worker shutdown, Runtime Error occur, because Event loop is interrupted.
[RuntimeError: Event loop stopped before Future completed.]

Here is my code.

@sanic_app.listener('before_server_start')
async def setupRedis(app, loop):
    app.redis = await loop.create_task(setRedisPool(app.config))
    if not app.redis:
        app.stop() # This part what i want to change.
    logger.debug('Redis setup finished')
async def setRedisPool():
    config = config.from_envvar('MY_SETTING')

    try:
        db = {}

        for key in config['REDIS']:
            redisSettings = config['REDIS'][key]
            address = (redisSettings.pop('host'), redisSettings.pop('port'))
            if not redisSettings.get('password'):
                redisSettings.pop('password')

            # In this code, TimeoutError occur once in a while
            redis = await create_redis_pool(address, timeout=3, maxsize=5, **cfg)
            db.update({key: redis})
        return db
    except Exception as e:
        logger.exception(e)

Could you give me a great hint for restart worker?
I’d like to restart gunicorn worker, when redis connection has TimeoutError.

Try something like this:

async def setRedisPool(app: Sanic):
    for _ in range(3):
        logger.info(".")
        await asyncio.sleep(1)

    try:
        logger.info("raising")
        raise asyncio.TimeoutError("Pretend this is real timeout")
    except asyncio.TimeoutError:
        logger.info("caught")
        app.stop()
        logger.info("stopped")

@app.listener("after_server_start")
async def setupRedis(app: Sanic, _):
    app.add_task(setRedisPool)

Also, if you are going to use gunicorn, I would sugges using it with uvicorn worker.

$ gunicorn server:app -b 127.0.0.1:8888 -k uvicorn.workers.UvicornWorker