Scheduling of Tasks in Django

Asked

Viewed 988 times

1

Guys is the following, in Django things only happen when some user accesses your application.

AN EXAMPLE (fictional)

Let’s imagine that you created an application in which the user enters and records small reminder texts, more or less as if they were a post-it, for him to consult every day and check the activities that can not forget.

The user needs to enter the application to consult their reminders for the current date and to add new reminders for future dates.

THE NEW NEED

Now imagine that you want to implement a new functionality so that every day your application sends an email listing of user reminders for that starting day.

THE REFLECTION ON THE CASE

Note that originally all actions that occur in the application depend on a user access, but for this new functionality we will need the system to initiate an action automatically without waiting for a user action.

It would be a kind of service running that every day at a certain time check the reminders of each user, prepare each message and send them.

WHAT I THOUGHT TO DO

It crossed my mind to create a thread that runs all the time in parallel and when arriving at the scheduled time triggers the necessary routines.

It seems to make some sense, but I’m not sure if there is a better option to do this and still what the pros and cons of this structure would be, plus some possible impact on the system’s resource consumption.

Important: I have no difficulty in preparing the routines they perform actions (check reminders, prepare messages and send emails), my problem is about how to create that schedule that will trigger this process automatically.

You already had to create something like this with Django, as you did?

  • 1

    The ideal is to schedule a task in the OS (e.g., on *NIX systems, via cron) that calls a Django command (e.g..: via manage.py) which then does what you want. Or else use a tool like the Celery (never used, but what I’ve been researching is the most recommended way to do it). P.S. I do not give a more complete answer because I have no practical experience.

1 answer

2


The Django’s Basic Tutorial guides the creation of a custom command for the execution of external routines. In your case, by the description of the problem, I believe you can follow this line. Here follows the link to Writing custom Django-admin commands that has a detailed explanation on the subject.

In general lines you will have to:

  1. Write your Command:

    class Command(BaseCommand):
        help = 'Command Customizado Teste'
    
        def add_arguments(self, parser):
            parser.add_argument('parametro', nargs='+', type=str)
    
        def handle(self, *args, **options):
            print("Chamou a execução deste command")
            print(options['parametro'])                 
    
  2. Put Command in the management/Commands directory of your app (in the Django example (dir_project)/polls/management/Commands). The command name will be the name of the file (module) you created.

  3. To check if your Command has been recognized by Django, type python Manage.py. You’ll see something similar to this:

    Type 'manage.py help <subcommand>' for help on a specific subcommand.
    
    Available subcommands:
    
    [auth]
        changepassword
        createsuperuser
    
    [seu app]
        seu_command
    
    [django]
        check
        compilemessages
        createcachetable
        dbshell
        diffsettings
        dumpdata
        flush
        inspectdb
        loaddata
        makemessages
        makemigrations
        migrate
        sendtestemail
        shell
        showmigrations
        sqlflush
        sqlmigrate
        sqlsequencereset
        squashmigrations
        startapp
        startproject
        test
        testserver
    
    [sessions]
        clearsessions
    
    [staticfiles]
        collectstatic
        findstatic
        runserver
    
  4. To run it use (check the documentation for parameters):

    python manage.py seu_command "seu parametro"
    
  5. Finally, after your Command is finished and tested, schedule its execution in the crontab or OS task scheduler you use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.