0

I want to create cronjobs dynamically, not by manually writing them in the CRONJOBS variable in the config.settings.py module source code

Here is my code:

from django.conf import settings
from sender.auxfunc.create_cronjob import func


class MailingCreateView(CreateView):
    model = ConfigMailing
    user = self.request.user
    fields = '__all__'
    template_name = 'sender/profile.html'
    success_url = reverse_lazy('sender:profile')

    def form_valid(self, form):
        self.object = form.save()
        create_cronjob = func.format(user, mailing)
        
        #block of code that creates a cronjob function in the client's individual folder. 
        #This block works correctly
        target_dir = f'sender/crons/{user}/{self.object.pk}'
        with open(f'{target_dir}/cron.py', 'w', encoding='utf-8') as f:
            f.write(f'{create_cronjob}')

        cronjob = (self.object.cron_period, self.object.cron_path)
        settings.CRONJOBS.append(cronjob)
        os.system('python3 manage.py crontab add')
        os.system('python3 manage.py crontab show >> show_crons_log.txt')
        print(settings.CRONJOBS)    #cronjobs are added to the variable and displayed correctly
        
        return super().form_valid(form)

When creating multiple instances of the Mailing class in succession, the print(settings.CRONJOBS) command prints all created cronjobs.

However, running the python3 manage.py crontab show command shows that the cronjobs do not exist.

The django-crontab documentation is very sparse, but I conclude that the program creates registers crontab only from the source code of the variable CRONJOBS from module config.settings.py which is empty

Is it possible to somehow correct the situation? Thanks for any answer.

The only solution I see is to rewrite the CRONJOBS variable with loops and regular expressions. But this is insecure and will kill performance and has no prospects for scaling the project

Vsevolod
  • 21
  • 4

0 Answers0