Overview
The CronJob class wraps any callable (including Swarms agents) and turns it into a scheduled job that runs at specified intervals. It provides robust scheduling, error handling, retry logic, and execution tracking with optional callback support for output customization.Constructor
Create a CronJob instance to schedule recurring agent executions.Parameters
The Swarms Agent instance or callable to be scheduled
The interval string (e.g., “5seconds”, “10minutes”, “1hour”)
Optional unique identifier for the job. If not provided, one will be generated.
Optional callback function to customize output processing.Signature:
callback(output: Any, task: str, metadata: dict) -> Anyoutput: The original output from the agenttask: The task that was executedmetadata: Dictionary containing job_id, timestamp, execution_count, etc.- Returns: The customized output
Attributes
Unique identifier for the job
Flag indicating if the job is currently running
Number of times the job has been executed
Timestamp when the job was started
Methods
run
Schedule and run the job with a specified task.The task string to be executed by the agent
Additional parameters to pass to the agent’s run method (e.g.,
img, imgs, correct_answer, streaming_callback)CronJobConfigError: If agent or interval is not configuredCronJobExecutionError: If task execution fails
- Schedules the task according to the configured interval
- Starts the background execution thread
- Blocks until KeyboardInterrupt (Ctrl+C) is received
- Automatically stops on interrupt
batched_run
Run multiple tasks sequentially with the same schedule.List of task strings to execute
Additional parameters to pass to the agent’s run method
List of results from each task execution
start
Manually start the scheduled job.CronJobExecutionError: If the job fails to start
- Creates a daemon thread for job execution
- Sets
is_runningto True - Records
start_time - If already running, logs a warning
stop
Stop the scheduled job.CronJobExecutionError: If the job fails to stop properly
- Sets
is_runningto False - Waits up to 5 seconds for thread to terminate
- Clears the schedule
- Logs warning if thread doesn’t terminate gracefully
set_callback
Set or update the callback function for output customization.Callback function with signature:
callback(output, task, metadata) -> Anyget_execution_stats
Get execution statistics for the cron job.Dictionary containing:
job_id: Job identifieris_running: Current running statusexecution_count: Number of executionsstart_time: Start timestampuptime: Time elapsed since start (seconds)interval: Configured interval string
Interval Formats
Theinterval parameter accepts strings in the format <number><unit>:
Supported Units
- Seconds:
"5seconds","30second" - Minutes:
"10minutes","1minute" - Hours:
"2hours","1hour"
Examples
Complete Examples
Basic Scheduled Analysis
Multi-Stock Analysis with Batching
Custom Callback for Output Processing
Image Analysis with Scheduling
Monitoring Execution Stats
Exception Handling
The CronJob class defines several custom exceptions:CronJobError
Base exception class for all CronJob errors.CronJobConfigError
Raised for configuration errors.CronJobScheduleError
Raised for scheduling related errors.CronJobExecutionError
Raised for execution related errors.Best Practices
- Use descriptive job IDs: Make job identifiers meaningful for tracking
- Set appropriate intervals: Choose intervals based on task complexity and resource availability
- Implement callbacks: Use callbacks for logging, saving results, or sending notifications
- Monitor execution stats: Regularly check stats to ensure jobs are running as expected
- Handle interrupts: Always wrap
run()in try-except to handle KeyboardInterrupt - Consider agent limits: Ensure your agent’s
max_loopsis appropriate for scheduled tasks - Log failures: Enable verbose mode and implement proper error logging
- Test intervals: Start with longer intervals and optimize based on performance
- Resource management: Be mindful of API rate limits and costs with frequent scheduling
- Graceful shutdown: Always call
stop()when terminating scheduled jobs
Thread Safety
CronJob uses threading for background execution:- Daemon threads are used to prevent blocking program exit
- Thread-safe scheduling with the
schedulelibrary - Proper cleanup on stop() with timeout handling
Callback Metadata
The callback function receives a metadata dictionary with:- Logging execution history
- Conditional processing based on execution count
- Time-based analysis
- Debugging and monitoring