from random import randint

from django.db import connection, connections
from uwsgidecoratorsfallback import cron, postfork

from ocyan.main.utils import run_exclusive


# pylint: disable=unused-argument
@cron(randint(0, 59), 0, -1, -1, -1, target="spooler")  # at 0:00
def clearsessions(args):
    # the spooler is forked so the db connection might be closed
    try:
        if not connection.is_usable():
            connection.close()
    except AttributeError:
        connection.close_if_unusable_or_obsolete()

    run_exclusive("clearsessions")


@postfork
def cleanupdb():
    for conn in connections.all():
        try:
            if not conn.is_usable():
                conn.close()
        except AttributeError:
            conn.close_if_unusable_or_obsolete()
