Celery dynamic tasks / hiding Celery implementation behind an interface

走远了吗. 提交于 2019-12-07 08:50:57

问题


I am trying to figure out how to implement my asynchronous jobs with Celery, without tying them to the Celery implementation.

If I have an interface that accepts objects to schedule, such as callables (Or an object that wraps a callable):

ITaskManager(Interface):
    def schedule(task):
        #eventually run task

And I might implement it with the treading module:

ThreadingTaskManager(object)
    def schedule(task):
        Thread(task).start() # or similar

But it seems this couldn't be done with celery, am I right?


回答1:


Perhaps one, albeit quite ugly, solution might be to define one celery task which dynamically loads the task object that is passed as an argument:

@celery.task
def taskrunner(taskname):
    taskModule = __import__(taskname)
    taskModule.run()

CeleryTaskManager(object)
    def schedule(task):
        taskrunner.delay(task.__file__)


from mytask import run

CeleryTaskManager().schedule(run)


来源:https://stackoverflow.com/questions/12653745/celery-dynamic-tasks-hiding-celery-implementation-behind-an-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!