How to manage a stop or restart of a task from Django-based site?

Viewed 301

I'll be running a script in a server which will automatically create model instances in a database. The idea is to use a infinite loop (e.g while True:) which will be endlessly creating instances until I somehow stop it. I want to use Django to nicely check from my website how big my database is, and from there I want to stop or restart it. What could be a good approach here? I was thinking about Celery, but I don't know how would I don't have clear how to stop it and it kind of looks like an overkill. Any suggestion?

1 Answers

A simple solution is to have a class that saves to the db the name of the script and whether it should keep running:

class ScriptTracker():
    name = models.Charfield()
    keep_running = models.BooleanField()

Then your script would just check the db every loop to see if it should stop:

def my_script():

    while True:

        if not ScriptTracker.objects.get(name="my_script").keep_running:
            # stop running
            return

        # creating an instance in the db
        MyObject.objects.create(name="helloworld")
        
  1. Create the ScriptTracker object

ScriptTracker.objects.create(name="my_script", keep_running=True)

  1. Start your script running, could be done simple if script is built as a management command:

python manage.py my_script

Related