aaronrai24 / DollarDiscordBot

All-in-one discord bot that plays music, moderates, and gets video game stats
MIT License
1 stars 0 forks source link

Add proper handling for shutdowns #51

Closed aaronrai24 closed 1 year ago

aaronrai24 commented 1 year ago

Bug report: We should be closing the DB connection and cleaning up any asynchronous threads, this should resolve the terminal freezing issues we have been seeing in our dev environments

Submitted by: mfcash#0 Server: mfDiscord

aaronrai24 commented 1 year ago

This should get us started,

SIGINT (Signal Interrupt): This signal is typically triggered by pressing Ctrl+C in the terminal or sending the signal directly to the process. It's commonly used to request an orderly termination of a process by allowing it to perform cleanup tasks before exiting.

SIGTERM (Signal Terminate): This signal is a generic request for termination. It's commonly used to gracefully stop a process, allowing it to clean up resources and exit gracefully.

def shutdown_handler(signum, frame):
    print('Shutting down...')
    db.close()  # Close the database connection
    client.loop.stop()

signal.signal(signal.SIGINT, shutdown_handler)
signal.signal(signal.SIGTERM, shutdown_handler)

client.run(DISCORD_TOKEN)
aaronrai24 commented 1 year ago

Refactored to use tasks.loop() rather than manually creating a thread, add validate_db.start() to the on_ready method to start the task. Updated code:

async def validate_connection():
    try:
        cursor = mydb.cursor()
        cursor.execute("SELECT 1")
        cursor.fetchall()
        cursor.close()
        logger.debug('Executed validation query')
        return True
    except mysql.connector.Error as error:
        logger.error(f'Error validating connection: {error}')
        return False

# Periodically validate the connection
@tasks.loop(seconds=60)
async def validate_db():
    await validate_connection()