Django模型和Celery定期任务

问题描述 投票:0回答:3

我正在与Django一起开展物联网项目。我不喜欢做繁琐的编码。这里的问题是我有一个模型名称期间如下:

class Period(models.Model):
      number = models.PositiveIntegerField(primary_key=True)
      start_time = models.TimeField()
      end_time = models.TimeField()

另外,我希望我的Celery在Period.end_time做一些事情并添加此代码。 mysite / app / tasks.py中的代码。

@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    all_periods = Period.objects.all()
    for period in all_periods:
        hour = period.end_time.hour
        minute = period.end_time.minute
        sender.add_periodic_task(
            crontab(hour=hour, minute=minute),
            do_some_thing.s()
        )
@task
def do_some_thing():
      #do_some_thing

这是其他文件:

#mysite/mysite/celery.py
from __future__ import absolute_import
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smartschool.settings')
app = Celery('smartschool')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

#mysite/mysite/__init__.py
from __future__ import absolute_import, unicode_literals
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__=['celery_app']

#mysite/mysite/settings.py ##Celery part.
CELERY_BROKER_URL = 'amqp://'
CELERY_RESULT_BACKEND = 'rpc://'
CELERY_ACCEPT_COTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Ho_Chi_Minh'
CELERY_IMPORT = ('timetable.tasks')
CELERY_BEAT_SCHEDULE = {
    #'test':
    #{
    #    'task': 'timetable.tasks.hello',
    #    'schedule': 10.0,
    #},
    'system_on':
    {
        'task': 'timetable.tasks.system_on',
        'schedule': crontab(hour=7, minute=0)
    },
    'system_off':
    {
        'task': 'timetable.tasks.system_off',
        'schedule': crontab(hour=17, minute=30)
    },
}

为CELERY_SHEDULE_BEAT添加的定期任务工作正常,但add_periodic_task函数添加的任务没有。英语不是我的母语;请原谅我的帖子上的任何错误。

django django-models celery celerybeat periodic-task
3个回答
0
投票

您可以将@periodic_task装饰器用于crontab任务,在项目运行后,您应该运行此代码。 celery -A YOURPROJETNAME worker -l -b info


0
投票

另一种运行这样的crontab作业的方法。

@task
def my_task():
   //your code 

和你的celery.py文件

app.conf.beat_schedule = {
    'my_task': {
        'task': 'Path.tasks.my_task',
        'schedule': crontab(minute='*/5'),
        'args': []
    },
}

0
投票

我想我已经想通了。通过将@ task.on_after_configure.connect更改为@ task.on_after_finalize.connect,add_periodic_task函数可以正常工作,但是当我有11个Period实例时,只添加了一个任务!

© www.soinside.com 2019 - 2024. All rights reserved.