【问题标题】:How to initialize repeating tasks using Django Background Tasks?如何使用 Django 后台任务初始化重复任务?
【发布时间】:2018-09-07 06:14:29
【问题描述】:

我正在开发一个 django 应用程序,它从 Dropbox 读取 csv 文件,解析数据并将其存储在数据库中。为此,我需要后台任务来检查文件是否被修改或更改(更新),然后更新数据库。 我尝试了“Celery”,但未能使用 django 对其进行配置。然后我发现 django-background-tasks 比 celery 配置起来要简单得多。 我的问题是如何初始化重复任务?
documentation 中有描述 但我找不到任何解释如何使用 repeatrepeat_until 或文档中提到的其他常量的示例。
任何人都可以用例子解释以下内容吗?

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


重复以秒为单位。提供了以下常量: Task.NEVER(默认)、Task.HOURLY、Task.DAILY、Task.WEEKLY、 Task.EVERY_2_WEEKS,Task.EVERY_4_WEEKS。

【问题讨论】:

    标签: python django asynchronous background-task


    【解决方案1】:

    当您确实需要执行特定函数 (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
    


    执行程序
    1. 请求到达 url,因此它会分派到相应的视图,这里是myview()
    2. 执行get_csv(creds, repeat=100) 行,然后在DB 中创建async task(现在不会执行该函数)
    3. 将 HTTP 响应返回给用户。

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

    【讨论】:

    • get_csv(creds, repeat=100) 不起作用。 repeat 是函数中的意外参数。 @杰林
    • 我不这么认为,因为它对我很有效。您可以添加所有相关代码吗?
    • Django Shell 调用 get_csv(creds, repeat=100) 函数。如果您仍然收到 unexpected argument 错误,则意味着您的代码中缺少某些内容
    • 我的错,实际上我使用的是 Visual Studio Code,它引发了意外的参数错误,但是当我尝试 python manage.py process_tasks 时它起作用了。谢谢你。 @杰林
    【解决方案2】:

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

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

    假设您希望重复此任务每天直到 2019 年元旦,您将执行以下操作

    import datetime
    new_years_2019 = datetime.datetime(2019, 01, 01)
    notify_user(some_id, repeat=task.DAILY, repeat_until=new_years_2019)
    

    【讨论】:

    • notify_user(some_id, repeat=task.DAILY, repeat_until=new_years_2019) 中有意外的参数repeat 和repeat_until。我应该在哪里调用 notify_user? @sytech
    • 嗯。您确定将装饰器添加到函数中吗?我刚刚对此进行了测试,对我来说效果很好。
    • 成功了。问题出在 Visual Studio 代码中。谢谢你。但是repeat=Task.DAILY 不起作用。只接受数字参数。为什么这样? @sytech
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多