Celery worker로 병렬 처리

2023. 12. 20. 21:16개발/Celery

728x90
반응형

Celery에서 큰 작업을 분산 처리하려면 작업을 작은 단위로 분할하여 처리하도록 구성하는 것이 일반적입니다. 이를 통해 여러 워커에서 동시에 실행되도록 하고, 전체 작업 시간을 단축할 수 있습니다. 이것은 Celery의 기능 중 하나인 Task Chaining 또는 Subtasks를 활용하여 수행됩니다.

다음은 큰 작업을 분할하고 동시에 실행하는 방법에 대한 예시입니다.

# externalAPI/tasks.py

from celery import Celery, group
from celery.schedules import crontab
from celery.utils.log import get_task_logger

app = Celery('app')
logger = get_task_logger(__name__)

@app.task
def process_chunk(start, end):
    # 실제 작업 처리 로직
    logger.info(f'Processing chunk from {start} to {end}')

@app.task
def report_date_daliy():
    # 큰 작업을 여러 작은 작업으로 분할
    total_chunks = 10
    chunk_size = 1

    chunks = [(i, i + chunk_size) for i in range(0, total_chunks * chunk_size, chunk_size)]

    # 작은 작업들을 그룹으로 묶어 동시에 실행
    group(process_chunk.s(start, end) for (start, end) in chunks)()

# 스케줄링 설정
app.conf.beat_schedule = {
    'report-data-daliy-crontab': {
        'task': 'app.tasks.daliy_def',
        'schedule': crontab(minute=20, hour=6),
    },
}

이 예시에서 report_date_daliy 작업은 큰 작업을 10개의 작은 작업으로 나누고, process_chunk 작업을 호출하여 분할된 작업들을 동시에 실행합니다. 이렇게 하면 작은 작업들이 여러 워커에서 동시에 실행될 수 있으며, 전체 작업 시간을 단축할 수 있습니다.

'개발 > Celery' 카테고리의 다른 글

celery 시간 확인하기  (0) 2023.12.17
Django-Celery 초급 가이드  (0) 2023.12.11
Celery의 튜토리얼  (0) 2023.12.10