Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize repeating tasks using Django Background Tasks?

I'm working on a django application which reads csv file from dropbox, parse data and store it in database. For this purpose I need background task which checks if the file is modified or changed(updated) and then updates database. I've tried 'Celery' but failed to configure it with django. Then I find django-background-tasks which is quite simpler than celery to configure. My question here is how to initialize repeating tasks?
It is described in documentation but I'm unable to find any example which explains how to use repeat, repeat_until or other constants mentioned in documentation.
can anyone explain the following with examples please?

notify_user(user.id, repeat=<number of seconds>, repeat_until=<datetime or None>)


repeat is given in seconds. The following constants are provided: Task.NEVER (default), Task.HOURLY, Task.DAILY, Task.WEEKLY, Task.EVERY_2_WEEKS, Task.EVERY_4_WEEKS.

like image 750
Azeem Avatar asked Mar 28 '18 13:03

Azeem


Video Answer


2 Answers

You have to call the particular function (notify_user()) when you really need to execute it.
Suppose you need to execute the task while a request comes to the server, then it would be like this,

@background(schedule=60)
def get_csv(creds):
    #read csv from drop box with credentials, "creds"
    #then update the DB

def myview(request):
    # do something with my view
    get_csv(creds, repeat=100)
    return SomeHttpResponse


Excecution Procedure
1. Request comes to the url hence it would dispatch to the corresponding view, here myview()
2. Excetes the line get_csv(creds, repeat=100) and then creates a async task in DB (it wont excetute the function now)
3. Returning the HTTP response to the user.

After 60 seconds from the time which the task creation, get_csv(creds) will excecutes repeatedly in every 100 seconds

like image 93
JPG Avatar answered Sep 26 '22 03:09

JPG


For example, suppose you have the function from the documentation

@background(schedule=60)
def notify_user(user_id):
    # lookup user by id and send them a message
    user = User.objects.get(pk=user_id)
    user.email_user('Here is a notification', 'You have been notified')

Suppose you want to repeat this task daily until New Years day of 2019 you would do the following

import datetime
new_years_2019 = datetime.datetime(2019, 01, 01)
notify_user(some_id, repeat=task.DAILY, repeat_until=new_years_2019)
like image 40
sytech Avatar answered Sep 22 '22 03:09

sytech