Celery 사용법
Celery
Celery
는 장고의 비동기 작업을 처리하는 라이브러리이다.
작업에 사용하는 데코레이터 다음 두가지가 있다.
@app.task
: 작업에 사용할 함수 데코레이터@shared_task
: 앱과 관계 없이 전역에서 사용 가능
기본 설정
django 설정에 다음 항목 추가
CELERY_ACCEPT_CONTENT = ['application/json']CELERY_TIMEZONE = 'Asia/Seoul'CELERY_ENABLE_UTC = 'False'
project/project/celery.py
from __future__ import absolute_import, unicode_literalsimport osfrom celery import Celeryfrom django.conf import settings# set the default Django settings module for the 'celery' program.os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<설정 파일 경로>')app = Celery('testapp_task')# Using a string here means the worker doesn't have to serialize# the configuration object to child processes.# - namespace='CELERY' means all celery-related configuration keys# should have a `CELERY_` prefix.app.config_from_object('django.conf:settings', namespace='CELERY')# Load task modules from all registered Django app configs.app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)@app.task(bind=True)def debug_task(self):print('Request: {0!r}'.format(self.request))
project/app/tasks.py
from __future__ import absolute_import, unicode_literalsfrom celery import shared_task@shared_taskdef test():print('Task start...')
커맨드라인에서 다음을 입력
celery -A <prject> worker -l <log level>
작업 실행
로컬 실행
from test.tasks import testtest.apply_async(args=[arg1, arg2], kwargs={'kwarg1': 'x', 'kwarg2': 'y'})test.delay(arg1, arg2, kwarg1='x', kwarg2='y')
원격 실행
from testapp.celery import appapp.send_task('test.tasks.test')
주기적 작업
주기적 작업에는 celery beat 사용.
기본적으로 UTC를 사용하나 앱에 timezone = 'Asia/Seoul'
를 설정하거나 app.conf.timezone = 'Asia/Seoul'
을 설정하거나 설정파일의 app.config_from_object
로 타임존 불러서 사용 가능