6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Celery でタスクのスケジュールさせたときのメモ

Last updated at Posted at 2018-04-25

概要

決まった時間や周期で何かタスクや関数を実行させたいときに使えるやつです。

環境

  • macOS 10.13.3
requirements.txt
Django==2.0.4
celery==4.1.0
redis==2.10.6
requests==2.18.4
requests-oauthlib==0.8.0
datetime==4.2

上の3つが django と celery まわりで必要なやつ。下3つは bot (app) で使っただけ。

git のリポジトリ。
TedKoba/nem_bot

準備

こういうノリで整える

django-admin startproject nem_bot
cd nem_bot
virtualenv env
source env/bin/activate
python manage.py startapp bot
nem_bot/celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nem_bot.settings')

app = Celery('nem_bot',
    broker='redis://localhost:6379/'
)
app.config_from_object('django.conf:settings')

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

nem_bot/settings.py
from celery.schedules import crontab

INSTALLED_APPS = [
    ...,
    'bot'
]


CELERYBEAT_SCHEDULE = {
    'post-every-hour': {
        'task': 'bot.tasks.tweet_nem_price',
        'schedule': crontab(hour='*')
    },
}
bot/tasks.py
from __future__ import absolute_import, unicode_literals
from nem_bot.celery import app
from bot.xem_bot import tweet_nem_price


@app.task
def scheduled_nem_bot():
    tweet_nem_price()

実行

これで動く。

celery -A nem_bot worker -B -l info

成果物

課題

公式にあるやり方で実装しても bot/tasks.py タスクが認識されてるのに呼び出されなかった。
Periodic Tasks

celery.py
from celery import Celery
from celery.schedules import crontab

app = Celery()

@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    # Calls test('hello') every 10 seconds.
    sender.add_periodic_task(10.0, test.s('hello'), name='add every 10')

    # Calls test('world') every 30 seconds
    sender.add_periodic_task(30.0, test.s('world'), expires=10)

    # Executes every Monday morning at 7:30 a.m.
    sender.add_periodic_task(
        crontab(hour=7, minute=30, day_of_week=1),
        test.s('Happy Mondays!'),
    )

@app.task
def test(arg):
    print(arg)

これだと sender.add_periodic_task()bot/tasks.py の中のタスクが呼び出せなかったお話。もうちょっと調べてみる予定。

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?