尝试使用 celery beat 在 django 中安排一个函数但给出错误

Tried scheduling a function in django with celery beat but giving error

试图在 Django 中安排函数 print_hello()。但是代码似乎不起作用。

这是 Django 项目布局。只给出了celery相关的文件。

- celery_test
    - celery_test
        - __init__.py
        - celery.py
        - tasks.py

_初始化_.py代码:

from .celery import app as celery_app

__all__ = ('celery_app',)

celery.py代码:

import os
from celery import Celery

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

app = Celery('celery_test')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.conf.schedule_beat = {
    'print-hello-every-2-seconds': {
        'task': 'tasks.print_hello',
        'schedule': 2,
    },
}
app.autodiscover_tasks()

tasks.py代码:

from celery import shared_task

@shared_task
def print_hello():
    print("Hello celery...")

在运行celery -A celery_test worker -l info之后,提示显示如下错误。

 -------------- celery@########## v4.4.7 (cliffs)
--- ***** -----
-- ******* ---- Windows-10-10.0.18362-SP0 2020-09-26 19:03:12
- *** --- * ---
- ** ---------- [config]
- ** ---------- .> app:         celery_test:0x2c34a320eb0
- ** ---------- .> transport:   amqp://guest:**@localhost:5672//
- ** ---------- .> results:     disabled://
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery


[tasks]


[2020-09-26 19:03:13,202: INFO/SpawnPoolWorker-1] child process 4856 calling self.run()
[2020-09-26 19:03:13,202: INFO/SpawnPoolWorker-3] child process 784 calling self.run()
[2020-09-26 19:03:13,211: INFO/SpawnPoolWorker-2] child process 8868 calling self.run()
[2020-09-26 19:03:13,220: INFO/SpawnPoolWorker-4] child process 4064 calling self.run()
[2020-09-26 19:03:14,922: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [WinError 10061] No connection could be made because the target machine actively refused it.
Trying again in 2.00 seconds... (1/100)

[2020-09-26 19:03:18,937: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [WinError 10061] No connection could be made because the target machine actively refused it.
Trying again in 4.00 seconds... (2/100)

安装了以下版本。

django 3.1.1
celery 4.4.7
django-celery-beat 2.0.0

已尝试将 celery 降级到 3.1.15。但是 django-celery-beat 2.0.0 不兼容。

你是 运行 RabbitMQ 吗? - Celery broker(也可以选择使用常用的celery broker Redis)。 RabbitMQ的默认端口是5672.

参考this 您还可以在上面提到的存储库中找到 @shared_task 的用法。