如何在芹菜中定期运行任务?

时间:2020-04-26 16:18:50

标签: python celery periodic-task

我想每10秒执行一次芹菜定期任务。这是我在celery.py中的代码:

    from __future__ import absolute_import, unicode_literals
    import os
    from celery import Celery 

     os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoCelery1.settings')
     app = Celery('DjangoCelery1')
     app.config_from_object('django.conf:settings', namespace='CELERY')
     app.autodiscover_tasks()   

     @app.on_after_finalize.connect
     def setup_periodic_tasks(sender, **kwargs):
             sender.add_periodic_task(10, test.s('hello'), name='add every 10')

    @app.task
    def test(arg):
        print(arg)
        with open("test.txt", "w") as myfile:
             myfile.write(arg)

然后我通过以下命令运行它:

celery -A DjangoCelery1 beat -l info

它似乎正在运行,并且在终端中,我给出以下消息:

celery beat v4.4.2 (cliffs) is starting.
__    -    ... __   -        _
LocalTime -> 2020-04-26 15:56:48
Configuration ->
    . broker -> amqp://guest:**@localhost:5672//
    . loader -> celery.loaders.app.AppLoader
    . scheduler -> celery.beat.PersistentScheduler
    . db -> celerybeat-schedule
    . logfile -> [stderr]@%INFO
    . maxinterval -> 5.00 minutes (300s)
[2020-04-26 15:56:48,483: INFO/MainProcess] beat: Starting...
[2020-04-26 15:56:48,499: INFO/MainProcess] Scheduler: Sending due task add every 10 (DjangoCelery1.celery.test)
[2020-04-26 15:56:53,492: INFO/MainProcess] Scheduler: Sending due task add every 10 (DjangoCelery1.celery.test)
[2020-04-26 15:56:58,492: INFO/MainProcess] Scheduler: Sending due task add every 10 (DjangoCelery1.celery.test)
[2020-04-26 15:57:03,492: INFO/MainProcess] Scheduler: Sending due task add every 10 (DjangoCelery1.celery.test)
[2020-04-26 15:57:08,492: INFO/MainProcess] Scheduler: Sending due task add every 10 (DjangoCelery1.celery.test)
[2020-04-26 15:57:13,492: INFO/MainProcess] Scheduler: Sending due task add every 10 (DjangoCelery1.celery.test)

但是,该任务未运行,并且没有打印的消息和创建的文本文件。 有什么问题吗?

1 个答案:

答案 0 :(得分:2)

这是节拍过程-现在您需要运行另一个过程:

celery -A tasks worker ...

这样,工作人员就可以消耗您通过节拍触发的任务并进行处理。