如何使用Django后台任务初始化重复任务? [英] How to initialize repeating tasks using Django Background Tasks?

查看:106
本文介绍了如何使用Django后台任务初始化重复任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


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

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.

推荐答案

在确实需要执行特定功能时,必须调用特定功能( notify_user()).
假设您需要在服务器收到请求时执行任务,就像这样,

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


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

从创建任务的时间起60秒后, get_csv(creds)将每隔 100秒


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

这篇关于如何使用Django后台任务初始化重复任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆