From ae1d582266be8d2d982e3dfa1d8a3e7bfc2d9b2a Mon Sep 17 00:00:00 2001 From: Charles Leifer Date: Fri, 13 Jan 2023 12:44:18 -0600 Subject: [PATCH] Add note on dynamic tasks. --- docs/guide.rst | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/guide.rst b/docs/guide.rst index 1d5ec714..e4580083 100644 --- a/docs/guide.rst +++ b/docs/guide.rst @@ -1008,6 +1008,33 @@ like of the "dynamic ptask" function: When the consumer executes the "schedule_message" tasks, our new periodic task will be registered and added to the schedule. +Run Arbitrary Functions as Tasks +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Instead of explicitly needing to declare all of your tasks up-front, you can +write a special task that accepts a dotted-path to a callable and run anything +inside of huey (provided it is available wherever the consumer is running): + +.. code-block:: python + + from importlib import import_module + + @huey.task() + def path_task(path, *args, **kwargs): + path, name = path.rsplit('.', 1) # e.g. path.to.module.function + mod = import_module(path) # Dynamically import the module. + return getattr(mod, name)(*args, **kwargs) # Call the function. + + # Example usage might be: + # foo.py + def add_these(a, b): + return a + b + + # Somewhere else, we can tell the consumer to use the "path_task" to import + # the foo module and call "add_these(1, 2)", storing the result in the + # result-store like any other task. + path_task('foo.add_these', 1, 2) + Reading more ------------