Locking Django management commands

I have a number of management commands running via cron and sometimes they take longer to run than the time imbetween jobs. I don't want two jobs runningin parallel so when I saw that Django Notification used lock files in its emission of notices, I wanted to apply that cleanly to my management commands.

So I created a decorator that would add a locking file based on the current module file name, which would ensure that there is only ever one process running at any time. Then all I have to do is simply decorate my management commands by applying the decorator to the handle method like so:

# load the deocrator
from decorators import handle_lock
    
class Command(BaseCommand):
    help = "Regular Management command."
   
    # decorate the handle
    @handle_lock
    def handle(self, *args, **options):
        # Do your stuff here

 

And volia the management command will only ever run in single file. Go ahead and try it out: