duck.automation¶
Classes¶
AutomationError: Custom exception for automation-related errors.AutomationThread: Threading class for executing automations.Automation: Base class for automating tasks, jobs, actions, etc.
Usage Example¶
import os
from duck.automation.dispatcher import DispatcherV1
from duck.automation.trigger import NoTrigger
class SimpleAutomation(Automation):
# Execute a shell script
def execute(self):
# Or use async def execute for asynchronous execution, but parse `async_` argument to automation.
os.system('bash some_script.sh')
# Instantiate the automation with specified parameters
automation = SimpleAutomation(
name="Sample Automation",
description="Sample automation",
start_time='immediate',
schedules=1,
interval=0,
) # Set automation schedules to -1 for infinite schedules
# Instantiate a trigger that executes immediately
trigger = NoTrigger()
# You can create a custom trigger by implementing the `check_trigger` method
# in your AutomationTrigger subclass and returning True or False based on
# whether the trigger condition is satisfied
# Create a dispatcher to manage and execute automations
dispatcher = DispatcherV1() # The first argument is the main running web application (optional)
# Register the trigger and automation with the dispatcher
dispatcher.register(trigger, automation)
dispatcher.start() # Listen for triggers and execute automations infinitely
# Alternatively, use a callback function for the automation task
def callback():
# Perform the automation tasks here
# Avoid using while loops; set the number of schedules to -1 for infinite schedules
pass
automation = Automation(
callback=callback,
name="Sample Automation",
description="Sample automation"
)
# Register the trigger and automation with the dispatcher
dispatcher.register(trigger, automation)
dispatcher.start() # Listen for triggers and execute automations infinitely
Module for automations used in automating tasks, jobs, actions, and more.
This module provides classes and utilities to define and manage automated tasks. It includes a base Automation class for creating and running tasks with various scheduling options, as well as supporting threading and callback functionalities.
Submodules¶
Package Contents¶
Classes¶
Automation class for automating tasks, jobs, actions, etc. |
|
Threading class for Automations execution. |
|
A placeholder automation class designed for testing or sampling purposes. |
Data¶
API¶
- class duck.automation.Automation(callback: callable = None, name: str = None, threaded: bool = True, async_: bool = False, start_time: datetime.datetime | str = 'immediate', schedules: int = 1, interval: float | int = None, description: str = None)[source]¶
Automation class for automating tasks, jobs, actions, etc.
Events:
on_pre_execute: Called before every execution cycle.on_post_execute: Called after every execution cycle.on_start: Called once when the automation starts.on_finish: Called once when the automation finishes.on_error: Called whenever there is an error during execution. Override this method to suppress or handle all errors.
Notes:
The
startmethod is the initial method to run an automation.The
callbackargument is optional; if not provided, theexecutemethod must be implemented.Provide a name and description for more descriptive Automations.
The
joinmethod can be used to stop the next execution cycle, meaning the automation will stop immediately before entering the next execution cycle.Using a while loop in the
callbackorexecutemethod will cause the automation to hang, andjoinwill not work if the callback is in a loop.The
joinmethod works properly before the next execution cycle or after the current execution cycle.
Automations can be asynchronously executed by providing the
async_argument.Initialization
Initialize the Automation class.
- Parameters:
callback – A callable to be executed whenever the automation runs. If you do not provide a callback, implement the ‘execute’ method.
name – The name of the Automation. Defaults to None.
threaded – Indicates whether to run the automation in a new thread. Defaults to True.
async_ – Indicates whether to run automation asynchronously. Defaults to False.
start_time – The datetime to start the Automation. It can be “immediate” or any specific datetime.
schedules – The number of times to run the Automation. Defaults to 1. Set to -1 for infinite schedules.
interval – The time period in seconds between successive runs of the Automation.
description – A brief description of the Automation. Defaults to an empty string.
- execute()[source]¶
This executes an automation. Do whatever task you want here e.g. running bash scripts or something else.
Example:
import os class SimpleAutomation(Automation): def execute(self): os.system('bash some_script.bash') automation = SimpleAutomation(start_time='immediate', schedules=1, interval=0) automation.start # start the automation
- property execution_cycles: int¶
Returns the number of times the automation has been executed (same as property ‘execution_times’).
- property execution_times: int¶
Returns the number of times the automation has been executed.
- property finished¶
Whether the automation has been stopped completely.
- property finished_at: datetime.datetime¶
The datetime where this automation finished.
- property first_execution: bool¶
Returns whether the automation has already been executed for the first time.
… admonition:: Notes
Take a look a property execution_times to see the number of times the Automation was Executed.
- get_thread()[source]¶
This returns the Thread for running automation.
… admonition:: Notes
The thread is only created once.
- property is_running: bool¶
Whether the automation is running or not.
- join()[source]¶
Wait for the automation to finish the current execution cycle and stop the execution
- property latest_error¶
Returns the latest exception encountered during execution.
- on_start()[source]¶
Method called once the execution has been started.
Notes:
Method “on_start” is called before method “on_pre_execute”
- property started_at: datetime.datetime¶
The datetime where this automation started.
- to_thread() duck.automation.AutomationThread[source]¶
This wraps an automation in new Thread so that it may be executed nicely without blocking any other automations execution.
- Returns:
Returns an automation in new thread.
- Return type:
- exception duck.automation.AutomationError[source]¶
Bases:
ExceptionAutomation based exceptions.
Initialization
Initialize self. See help(type(self)) for accurate signature.
- class duck.automation.AutomationThread(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None)[source]¶
Bases:
threading.ThreadThreading class for Automations execution.
Initialization
This constructor should always be called with keyword arguments. Arguments are:
group should be None; reserved for future extension when a ThreadGroup class is implemented.
target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.
args is a list or tuple of arguments for the target invocation. Defaults to ().
kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.init()) before doing anything else to the thread.
- on_stop()[source]¶
Method called whenever a thread finishes execution.
The callback set with method ‘set_on_stop_callback’ will be called if present.
- duck.automation.SampleAutomation¶
‘SampleAutomationBase(…)’
- class duck.automation.SampleAutomationBase(callback: callable = None, name: str = None, threaded: bool = True, async_: bool = False, start_time: datetime.datetime | str = 'immediate', schedules: int = 1, interval: float | int = None, description: str = None)[source]¶
Bases:
duck.automation.AutomationA placeholder automation class designed for testing or sampling purposes.
This automation is intentionally empty and does not perform any actions. It can be used as a base for creating more complex automations or for testing automation systems without side effects.
Use this class when you need a no-op (no operation) automation that will not alter the application’s state or behavior during execution.
Initialization
Initialize the Automation class.
- Parameters:
callback – A callable to be executed whenever the automation runs. If you do not provide a callback, implement the ‘execute’ method.
name – The name of the Automation. Defaults to None.
threaded – Indicates whether to run the automation in a new thread. Defaults to True.
async_ – Indicates whether to run automation asynchronously. Defaults to False.
start_time – The datetime to start the Automation. It can be “immediate” or any specific datetime.
schedules – The number of times to run the Automation. Defaults to 1. Set to -1 for infinite schedules.
interval – The time period in seconds between successive runs of the Automation.
description – A brief description of the Automation. Defaults to an empty string.