讓 Celery 跑成 Daemon

在處理 Python 非同步作業或排程作業的時候,通常會使用 Celery , 但預設啟動 Celery 是透過下列的方式:

celery -A proj worker -l info

如果沒有掛在 Screen 裡或是透過其它方式跑到背景,不小心關掉 console, celery 就會停止運作了,所以必須要讓 Celery Daemon 化,也不會太複雜,以下說明步驟:

  1. 到 Github 上把 Celeryd 的 script 下載下來,放到 /etc/init.d/celeryd
  2. 如果 Project 有使用到環境變數,而環境變數又剛好寫在 .bashrc 裡,記得在 celeryd 的檔案裡加一行 source ~/.bashrc 避免 Celery 啟動的時候,找不到相關的環境變數。
  3. 接著把設定檔案放到 /etc/default/celeryd.

`

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Names of nodes to start most will only start one node:
CELERYD_NODES="worker1"

# Absolute or relative path to the 'celery' command:
# 如果有使用 virtualenvs ,路徑可能會像這樣
CELERY_BIN=""/root/.virtualenvs/project/bin/celery""

# App instance to use
# comment out this line if you don't use an app
CELERY_APP="proj"

# Where to chdir at start. Django Project 的位置
CELERYD_CHDIR="/var/www/proj"

# Extra command-line arguments to the worker
CELERYD_OPTS="--time-limit=300 --concurrency=8"

# %N will be replaced with the first part of the nodename.
CELERYD_LOG_FILE="/var/log/celery/%N.log"
CELERYD_PID_FILE="/var/run/celery/%N.pid"

# Workers should run as an unprivileged user.
# You need to create this user manually (or you can choose
# a user/group combination that already exists, e.g. nobody).
#
CELERYD_USER="celery"
CELERYD_GROUP="celery"

# If enabled pid and log directories will be created if missing,
# and owned by the userid/group configured.
CELERY_CREATE_DIRS=1

如果是透過 Root 權限來執行,必須export C_FORCE_ROOT="true",不然權限不合 Celery 也不會報錯。

設定好以後,可以透過 service celeryd start 來啟動 celery 或是 service celeryd stop 來停止。