pkdkk
pkdkk

Reputation: 3961

Run Django command from crontab, only one concurrently

I have a Django commend "script" that i running every 20 second

like this:: (only shows part of it, and works fine ;))

* * * * * /manage.py btupdate
* * * * * sleep 20; /manage.py btupdate
* * * * * sleep 40; /manage.py btupdate

My problem is that the "command script" sometimes may take more than 20 sec. to execute, and I don't want to start another job before the last job has stopped.

How to solve that? ;)

Upvotes: 1

Views: 404

Answers (2)

1844144
1844144

Reputation: 657

You can use file as indicator of work. (maybe you can use process id too, but solution with file is simple enought)

  1. check if /tmp/iam_working exists
  2. if not exist - create it and run your script ( if exists - do nothing)
  3. remove file after jobs end

in bash:

if [ ! -f /tmp/iam_working ] ; then touch /tmp/iam_working; yourcommands; rm /tmp/iam_working; fi

Upvotes: 3

MadeOfAir
MadeOfAir

Reputation: 3183

You can also use a database model as an indicator of work. It's arguably cleaner than the file-based approach.

# models.py
from django.db import models
class CommandStatus(models.Model):
    running = models.BooleanField(default=False, null=False, blank=True)

Create an instance from the model:

from myapp.models import CommandStatus
indicator = CommandStatus.objects.create()

Use the instance in your command:

status = CommandStatus.objects.all()[0]
if not status.running:
    status.running = True
    status.save()
    # do stuff
    status.running = False
    status.save()

Upvotes: 2

Related Questions