如何使用Django后台任务来初始化重复任务?

7 人关注

我正在开发一个django应用程序,它从dropbox读取csv文件,解析数据并将其存储在数据库中。为此,我需要后台任务来检查文件是否被修改或改变(更新),然后更新数据库。 我已经试过了' Celery ',但未能将其与django进行配置。然后我发现 django-background-tasks 这比celery的配置要简单得多。 我的问题是如何初始化重复的任务?
It is described in 文件 但我找不到任何例子来解释如何使用 重复 , 重复_until or other constants mentioned in 文件.
谁能用例子解释一下以下情况?

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

重复 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.

python
django
asynchronous
background-task
Azeem
Azeem
发布于 2018-03-28
2 个回答
JPG
JPG
发布于 2018-03-28
已采纳
0 人赞同

当你真正需要执行的时候,你必须调用特定的函数( notify_user() )。
假设你需要在一个请求来到服务器的时候执行任务,那么就会是这样的。

@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.请求来到网址,因此它将派发到相应的视图,这里myview()
2.挖掘行get_csv(creds, repeat=100),然后在DB中创建一个async task(它现在不会挖掘该功能)。
3. Returning the HTTP response to the user.

在任务创建的60秒后,get_csv(creds)会在每个100 seconds中重复执行。

get_csv(creds, repeat=100)不工作。 repeat是函数中的一个意外参数。@Jerin
JPG
我不这么认为,因为它对我很有效。你能添加你所有的相关代码吗?
JPG
调用 get_csv(creds, repeat=100) 函数,从 Django Shell .如果你仍然得到了 unexpected argument 的错误,这意味着你的代码中缺少一些东西。
我的错,实际上我使用的是Visual Studio Code,它出现了意外参数错误,但当我尝试 python manage.py process_tasks 时,它就成功了。谢谢你。@Jerin
sytech
sytech
发布于 2018-03-28
0 人赞同

例如,假设你有文档中的函数

@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')

假设你想重复这项工作每日 until 2019年的元旦 you would do the following