How to run a function with parameters periodicaly?

Issue

I have a form(DashboardData model) on my system that each user fills out. In this form, we are asking for a username, password, and a range to update for another system. Options in this range are once a week, once a month, and once a year.

Depending on which interval the user selects, I will run a function at those intervals. In this function, I will get the username and password from the form filled by the user as parameters. For example in form username, password, once a week is selected then I have to run myFunction(username, password) once a week.

I try to use apscheduler for this. But in apps.py I can not reach request.user, so, I cannot get the data. I have to take request.user for running my function.

forms.py

class SetupForm(forms.ModelForm):
    # Time
    PERIOD = (
        ('168', 'Once a week'),
        ('720', 'Once a month'),
        ('8766 ', 'Once a year'),
    )
    n_username = forms.CharField()
    n_password = forms.CharField(widget=forms.PasswordInput)
    period = forms.CharField(max_length=200, widget=forms.Select(choices=PERIOD)))

    class Meta:
        model = DashboardData
        fields = ('n_username', 'n_password','period')

models.py

class DashboardData(models.Model):
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) # request.user
    n_username = models.CharField(max_length=250)
    n_password = models.CharField(max_length=250)
    period = models.CharField(max_length=250)

functions.py

class myFunction():
    def __init__(self, n_user, n_password):
        self.time = datetime.now().strftime("%Y-%m-%d")
        self.location = a_url
        self.static_fields = {}
        self.index_name = "pre-" + self.zaman
        self.download_all(n_user, n_password)
        self.send_it()

apps.py

class DashboardConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'dashboard'
    def ready(self):
        start()

Solution

Celery periodic tasks will is good choice for running periodic tasks.

You can then use Django-celery-beat to control in database exactly when the functions are executed.

Specifically I draw attention to the cron tab scheduler

Answered By – Django Doctor

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published