预先在django中配置好celery,接下来着手配置下定时任务。
* 时区修改为本地时区 ``` # 在setttings.py 添加以下任意一行: CELERY_TIMEZONE = 'Asia/Shanghai' ``` 如果使用了django-celery-beat持久化到数据库,那么需要手动执行更新命令 ``` $ python manage.py shell >>> from django_celery_beat.models import PeriodicTask >>> PeriodicTask.objects.update(last_run_at=None) ``` *
使用periodic_task启用定时任务,这里可以看具体的crontab参数
# 在任意一个django app目录中新建一个tasks.py文件
from celery.task.schedules import crontab
from celery.decorators import periodic_task
import datetime
@periodic_task(run_every=crontab(minute="*/1"))
def print_hell_world():
print(f"{datetime.datetime.now()}:hello world!")
然后使用celery -A proj woker -B 启动
(crontab) lin@ubuntu:~/workspace/django/crontab$ celery -A crontab worker -B
-------------- celery@ubuntu v4.2.1 (windowlicker)
---- **** -----
--- * *** * -- Linux-4.4.0-112-generic-x86_64-with-debian-stretch-sid 2019-03-17 06:30:07
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: crontab:0x7f7c81adb0f0
- ** ---------- .> transport: amqp://guest:**@localhost:5672//
- ** ---------- .> results: disabled://
- *** --- * --- .> concurrency: 1 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
-------------- [queues]
.> celery exchange=celery(direct) key=celery
[2019-03-17 06:30:08,142: WARNING/MainProcess] /home/lin/.local/share/virtualenvs/crontab-zInQXnpg/lib/python3.6/site-packages/celery/fixups/django.py:200: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments!
warnings.warn('Using settings.DEBUG leads to a memory leak, never '
[2019-03-17 06:31:00,026: WARNING/ForkPoolWorker-2] 2019-03-17 06:31:00.026614:hello world!
[2019-03-17 06:32:00,023: WARNING/ForkPoolWorker-2] 2019-03-17 06:32:00.023664:hello world!
[2019-03-17 06:33:00,032: WARNING/ForkPoolWorker-2] 2019-03-17 06:33:00.032201:hello world!
使用django-celery-beat插件,可以将定时任务配置持久化,并且方便的通过django-admin进行修改, 更多详细信息
- pip install django-celery-beat
- setttings.py 添加如下配置
INSTALLED_APPS = (
...,
'django_celery_beat',
)
- python manage.py migrate
- 启动命令 添加 --scheduler django_celery_beat.schedulers:DatabaseScheduler
celery -A crontab_test worker -B -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler
- 在django admin后台会多出一个periodic tasks的配置栏