---
title: "Huey在Django下的使用"
url: "https://versun.me/using-huey-with-django"
markdown_url: "https://versun.me/using-huey-with-django.md"
format: "note"
published: "2024-01-18T14:40:00.000Z"
updated: "2026-01-05T05:30:44.000Z"
collections:
  - "Blog"
site: "Versun"
---

# Huey在Django下的使用

参考：  
[Huey](https://huey.readthedocs.io/en/latest/index.html)  
[官方文档Django](https://huey.readthedocs.io/en/latest/django.html#setting-things-up)

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

## 安装huey

参考：[https://huey.readthedocs.io/en/latest/installation.html](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](https://huey.readthedocs.io/en/latest/django.html#setting-things-up)

### 第一步是添加模块

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

### 第二步添加配置

```python
# settings.py

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

filename可自行设置其它路径

### 第三步添加任务

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

```python
# 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`
