简体   繁体   English

使用芹菜从另一个周期性任务中运行任务

[英]Run task from another periodic task with celery

I have periodic task which should trigger another task.我有周期性任务,应该触发另一个任务。 Final expected behavior: first task should collect some data from external service and then loop over this data (list) and call another task with passing over argument (current iteration in loop).最终预期行为:第一个任务应该从外部服务收集一些数据,然后遍历此数据(列表)并通过传递参数调用另一个任务(循环中的当前迭代)。 I want to have those tasks in loop being asynchronical.我想让这些任务在循环中是异步的。

I wrote code that runs a task in period, but I can't figure out how this task should call another task, because when I do it by .delay() method then nothing happens.我编写了在一段时间内运行任务的代码,但我无法弄清楚这个任务应该如何调用另一个任务,因为当我通过.delay()方法执行它时,什么也没有发生。

Here is some simplified code that I want to run:这是我想运行的一些简化代码:

@celery_app.task(name="Hello World")
def hello_world():
    print(f"HELLO WORLD PRINT")
    add.delay(2, 2)
    return 'Hello'


@celery_app.task
def add(x, y):
    with open(f"./{str(datetime.datetime.now())}.txt", 'w') as file:
        file.write(str(x+y))
    print(f"x + y = {x + y}")
    return x + y

For now hello_world() is running every 30 sec and as a result I receive HELLO WORLD PRINT in logs, but add task is not running.现在hello_world()每 30 秒运行一次,因此我在日志中收到 HELLO WORLD PRINT,但添加任务没有运行。 I can't see either print or file that should be created by this task.我看不到此任务应创建的打印件或文件。

Update for comment, here is how I use queue:更新评论,这是我如何使用队列:

celery_app.conf.task_routes = {
    "project.app.hello_world": {
        "queue": 'test_queue'
    },
    "project.app.add": {
        "queue": 'test_queue'
    },

There are few ways to solve the problem.解决问题的方法很少。

The obvious one is to put the queue name in the .apply_async, for an example add.apply_async(10, 10, queue="test_queue") .显而易见的是将队列名称放在 .apply_async 中,例如add.apply_async(10, 10, queue="test_queue")

Another solution is to put the queue into the task annotation, ie @celery_app.task(queue="test_queue") .另一种解决方案是将队列放入任务注解中,即@celery_app.task(queue="test_queue")

I have never configured task_routes, but I believe it is possible to specify it there like you tried...我从未配置过 task_routes,但我相信可以像您尝试的那样在那里指定它...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM