美文网首页
Django 自动注册tasks

Django 自动注册tasks

作者: alue | 来源:发表于2023-06-01 21:54 被阅读0次

最近,利用 Django + dramatiq + apscheduler 实现了异步消息队列功能,能够在Django应用中,方便的注册定时任务。使用方式如下:

# app/tasks.py
import dramatiq

from sigma_tools import cron


# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday)
# │ │ │ │ │
# * * * * *  

@cron("*/1 * * * *")
@dramatiq.actor
def some_task():
    print("每分钟都会执行这个任务")

开发的过程中,遇到一个问题,就是自己定义的定时任务存在tasks.py文件中,如果不在Django工程中引入这个文件,该定时任务将不会被注册。

一个办法是在每一个app的 __init__.py 文件中,显式的引入其 tasks.py 模块。由于Django会自动注册app,注册的同时,也就会发现__init__.py 文件中的tasks模块了。

但这个方法太土了,而且每个app都需要做一遍这个重复的工作,不够优雅。

优雅的方式,是在注册调度器时,自动发现并注册所有的tasks模块,代码如下:

from django.apps import apps
for app in apps.get_app_configs():
    try:
        __import__(f'{app.name}.tasks')
    except ImportError:
        pass

这样,开发时,只管声明tasks即可.

相关文章

网友评论

      本文标题:Django 自动注册tasks

      本文链接:https://www.haomeiwen.com/subject/avkpedtx.html