How to initialize repeating tasks using Django Background Tasks?

别来无恙 提交于 2020-02-02 06:58:52

问题


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.


回答1:


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




回答2:


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)


来源:https://stackoverflow.com/questions/49536561/how-to-initialize-repeating-tasks-using-django-background-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!