Huey在Django下的使用

参考: Huey 官方文档Django

对于小型的应用,轻量化的Huey非常适合做为Celery的替代品

安装huey

参考:https://huey.readthedocs.io/en/latest/installation.html

pip install huey 由于我直接使用sqlite,所以就不安装redis了

Django配置

参考:https://huey.readthedocs.io/en/latest/django.html#setting-things-up

第一步是添加模块

# settings.py
# ...
INSTALLED_APPS = (
    # ...
    'huey.contrib.djhuey',  # Add this to the list.
    # ...
)

第二步添加配置

# settings.py

HUEY = {
    'huey_class': 'huey.SqliteHuey',  
    'filename': DATA_FOLDER / "huey.sqlite3",  
    'consumer': {
        'workers': 1,
        'worker_type': 'thread',
    },
    "immediate": False,
}

filename可自行设置其它路径

第三步添加任务

在需要添加任务的app里创建tasks.py

# my_app/my_app/tasks.py
from huey import crontab
from huey.contrib.djhuey import periodic_task, task

@task()
def count_beans(number):
    print('-- counted %s beans --' % number)
    return 'Counted %s beans' % number

@periodic_task(crontab(minute='*/5'))
def every_five_mins():
    print('Every five minutes this will be printed by the consumer')

第四步运行

python ./manage.py run_huey

Contents