Cron Scheduling & Automated Task Orchestration
title: "Lesson 07 | Cron Scheduling & Automated Task Orchestration"
summary: "Use hermes cron to set up periodic automated tasks—scheduled reports, data collection, health checks. Gain a deep understanding of the Agent's operational mode and resource management as an "ever-vigilant assistant"."
sortOrder: 70
status: "published"
Hermes Agent Tutorial Series
Subtitle: Use hermes cron to set up periodic automated tasks—scheduled reports, data collection, health checks. Gain a deep understanding of the Agent's operational mode and resource management as an "ever-vigilant assistant".
🎯 Learning Objectives
- Master Hermes Agent's Cron scheduling mechanism: Understand how the Agent leverages Cron for periodic, intelligent task execution.
- Proficiently use the
hermes croncommand set: Learn to add, list, edit, delete, enable, and disable automated tasks. - Design and orchestrate complex automated workflows: Combine Cron scheduling with the Agent's Skills and Memory system to achieve advanced automation scenarios.
- Understand the Agent's automated task execution model and resource management: Explore how the Agent efficiently and responsibly executes tasks in an unattended state.
📖 Core Concepts Explained
One of the core philosophies of Hermes Agent is to be an "ever-vigilant assistant." To achieve this goal, merely responding to user commands is insufficient; it also needs the ability to proactively execute tasks. Cron scheduling is the key component that empowers the Agent with this capability, allowing it to independently initiate thought processes, perform operations, and provide results back to the user or store them, all according to a predefined schedule.
7.1 Cron Scheduling: The Agent's "Biological Clock"
In traditional Unix-like systems, cron is a daemon used to execute commands or scripts at a predetermined time, date, or interval. It acts like a precise "biological clock," ensuring that system maintenance tasks, data backups, and other operations run automatically on schedule. Hermes Agent elevates this concept to a new level; it doesn't just execute a simple shell command but triggers a complete "thought cycle" for the Agent.
When Hermes Agent's Cron scheduler is triggered, it will:
- Wake up the Agent core: If the Agent is idle, it will be awakened and necessary context loaded.
- Inject task instructions: The preset Prompt (instruction) will be passed to the Agent's Large Language Model (LLM) as user input.
- Intelligent decision-making and execution: The LLM will formulate an execution plan based on the Prompt, the Agent's Skills (see Lesson 03) and Memory (see Lesson 04), call the required tools, and generate a response.
- Result processing and feedback: The task execution result can be recorded in the Agent's Memory or sent to the user via a message gateway (see Lesson 05).
This intelligent Cron scheduling enables the Agent to:
- Scheduled reporting and summarization: Generate the latest market analysis, project progress reports, or news summaries every morning.
- Periodic data collection: Scrape stock prices, weather data, or website updates hourly and process them.
- System health checks and monitoring: Periodically check server status and service availability, and issue alerts if anomalies are detected.
- Automated content generation: Generate social media posts, email drafts, or blog articles on schedule.
Cron Expression Basics
The scheduling time for Cron tasks is defined by Cron expressions. A standard Cron expression consists of five fields, representing: minute, hour, day of month, month, day of week.
| Field | Allowed Values | Description |
|---|---|---|
| Minute | 0-59 | |
| Hour | 0-23 | (0 represents midnight) |
| Day of Month | 1-31 | |
| Month | 1-12 | |
| Day of Week | 0-7 | (0 and 7 both represent Sunday, 1 represents Monday) |
Special Characters:
*: Matches any value, meaning "every." For example,*in the minute field means every minute.,: Lists multiple values. For example,1,5means the 1st and 5th.-: Specifies a range. For example,9-17means from 9 AM to 5 PM./: Specifies an increment. For example,*/5in the minute field means every 5 minutes.?: Used only in the day-of-month and day-of-week fields, indicating no specific value is specified, often used to avoid conflicts.
Common Cron Expression Examples:
| Expression | Meaning |
|---|---|
0 0 * * * |
Execute daily at midnight 00:00 |
0 9 * * * |
Execute daily at 9:00 AM |
*/30 * * * * |
Execute every 30 minutes |
0 0 1 * * |
Execute on the 1st of every month at midnight 00:00 |
0 12 * * 1-5 |
Execute Monday to Friday at 12:00 PM |
Understanding Cron expressions is fundamental to configuring automated tasks. Hermes Agent's Cron scheduling feature, combined with its intelligent decision-making capabilities, elevates traditional scheduled tasks to a new level of intelligent automation.
7.2 hermes cron Command Details and Task Lifecycle
hermes cron commands are the core toolset for managing Hermes Agent's automated tasks. They provide an intuitive interface to add, view, edit, and delete scheduled tasks.
Task Management Command Overview
hermes cron add: Adds a new Cron task.hermes cron list: Lists all configured Cron tasks.hermes cron delete <task_id>: Deletes the specified Cron task.hermes cron enable <task_id>: Enables the specified Cron task.hermes cron disable <task_id>: Disables the specified Cron task.hermes cron edit <task_id>: Edits the properties of the specified Cron task.
hermes cron add Detailed Explanation
This is the most commonly used command for creating a new automated task.
hermes cron add \
--name "任务名称" \
--schedule "cron_表达式" \
--prompt "给 Agent 的指令" \
[--system-prompt "可选的系统指令"] \
[--model "可选的 LLM 模型名称"]
--name: A unique identifier for the task, facilitating identification and management.--schedule: The Cron expression, defining the task's execution frequency and time.--prompt: This is the core instruction the Agent receives when the task is triggered. You need to clearly describe the task the Agent needs to accomplish here.--system-prompt(Optional): Allows setting an independent system Prompt for this specific Cron task, overriding the Agent's default system Prompt. This is very useful for automated tasks that require a specific role or behavior.--model(Optional): Allows specifying an LLM model for this specific Cron task, overriding the Agent's default model configuration. This is very useful when certain tasks require specific model capabilities (e.g., longer context window, stronger reasoning ability).
Task Execution Flow and Status
When a Cron task is scheduled for execution, its lifecycle is roughly as follows:
graph TD
A[Cron Scheduler Triggered] --> B{Is Task Enabled?};
B -- Yes --> C[Hermes Agent Wakes Up];
C --> D[Load Task Context & Prompt];
D --> E[LLM Processes Prompt & Decides Actions];
E --> F{Utilize Skills/Tools?};
F -- Yes --> G[Agent Calls External Skills];
G --> H[Update Internal State/Memory];
H --> I[Generate Final Response/Output];
I --> J[Store Task Execution Result];
J --> K[Log Event & Go Dormant];
B -- No --> K;- Scheduler Trigger: According to the Cron expression, Hermes Agent's internal scheduler triggers the task at the specified time.
- Status Check: First, it checks if the task is in an Enabled state. If disabled, the task will be skipped.
- Agent Wake-up and Context Loading: The Agent core is activated, loading any specific configurations related to this task (e.g.,
--system-prompt,--model) and its persistent Memory. - Prompt Processing: The instruction defined in
--promptis fed into the LLM. The LLM will understand the task's intent based on its knowledge, Skills, and Memory. - Skill Invocation and External Interaction: If the task requires interaction with the external world (e.g., querying weather, sending emails, executing code), the LLM will decide to call the corresponding Skills (e.g.,
web_search,send_email, etc.). - Memory Update: Any important information or decisions generated during task execution will be recorded by the Agent into its long-term memory, so that future tasks or user queries can utilize it.
- Generate Output: The Agent generates the final result of the task, which could be a piece of text, a report summary, or a confirmation of a specific operation.
- Result Storage and Logging: The execution result and status (success, failure) of the task will be recorded for users to view via commands like
hermes logsorhermes doctor. - Agent Goes Dormant Again: After the task is completed, the Agent releases resources and enters a dormant state, awaiting the next trigger.
This refined task lifecycle management ensures that every automated task operates within the Agent's full capability framework, rather than just simple script execution. It allows the Agent to understand, execute, and learn like a true intelligent assistant.
7.3 Automated Task Orchestration Strategies: Combining Skills and Memory
The power of Hermes Agent lies in its modularity and self-evolving capabilities. Cron scheduling, as a trigger, truly shines when deeply integrated with the Agent's Skills and Memory systems, enabling the orchestration of highly intelligent and complex automated workflows.
1. Writing Effective Prompts
A good Prompt is the cornerstone of successful automated tasks. For Cron tasks, a Prompt is more than just a simple instruction; it's like a task specification that needs to clearly and explicitly guide the Agent to accomplish the following:
- Clearly define the task objective: What does the Agent ultimately need to achieve? For example: "Generate a daily market summary," "Check system health status."
- Specify information sources: If external information is needed, where should the Agent get it from? For example: "Use the
web_searchskill to find the latest financial news," "Readserver_status.logfrom the file system." - Define processing logic: How should the Agent process the acquired information? For example: "Filter news related to tech stocks," "Identify errors and warnings in the logs."
- Clarify output format and destination: What form should the results take? Where should they be sent? For example: "Output the summary in Markdown format and simulate sending it to me," "If an anomaly is found, generate a detailed report."
- Consider exceptional cases: How should the Agent respond when problems are encountered? For example: "If data cannot be retrieved, report the error and explain the reason."
Example Prompt Snippet:
"You are a professional financial analyst. Please use your `web_search` skill to retrieve today's latest global stock market news and key economic indicators. Then, based on this information, generate a concise daily market summary report, focusing on the potential impact on the technology sector. The report should include a title, key takeaways, and a brief analysis. Finally, simulate sending this report to me."
This Prompt clearly defines the Agent's role, required skills, processing steps, output format, and final delivery method.
2. Deep Integration with Skills
As described in Lesson 03, Skills are the bridge for the Agent to interact with the external world. Cron tasks can trigger the Agent to use one or more Skills to perform complex operations, thereby transcending the LLM's own knowledge limitations.
Integration Scenario Examples:
- Scheduled Data Collection and Analysis:
- Prompt: "Hourly, use the
web_searchskill to scrape the latest article titles from a specific website, and then use thetext_summarizeskill to generate a brief overview for each article. Consolidate the results into a list and record them in my Memory." - Involved Skills:
web_search(web scraping),text_summarize(text summarization).
- Prompt: "Hourly, use the
- Periodic System Health Check:
- Prompt: "Every day at 3 AM, use the
ssh_execskill to connect toprod-server-01and execute thedf -handsystemctl status nginxcommands. Analyze the output. If disk space is found to be below 10% or the Nginx service is not running, immediately generate a detailed alert report and record it in Memory." - Involved Skills:
ssh_exec(remote command execution),text_analysis(text analysis, performed by LLM).
- Prompt: "Every day at 3 AM, use the
- Automated Content Publishing:
- Prompt: "Every Monday at 8 AM, based on the past week's tech news (retrieved from Memory), generate a short blog post about future technology trends. Use the
image_generationskill to create an accompanying image for the article. Integrate the article and image content, and simulate publishing to my blog platform (assuming ablog_postskill exists)."
- Prompt: "Every Monday at 8 AM, based on the past week's tech news (retrieved from Memory), generate a short blog post about future technology trends. Use the
In this way, Cron tasks are no longer passively executed on schedule but become intelligent workflow initiators, driving the Agent to utilize its full capabilities to complete tasks.
3. Utilizing Memory to Maintain Task Context and Continuity
Lesson 04 details Hermes Agent's persistent memory system. For automated tasks, Memory is crucial as it provides the Agent with cross-session and cross-task continuity, enabling automated tasks to make decisions and evolve based on historical information.
Strategies for Utilizing Memory:
- Maintain task state: Store the latest status of automated tasks, last execution results, encountered problems, and other information in Memory. For example, a data collection task can record the ID of the latest data collected last time and continue from that ID on the next startup.
- Accumulate knowledge and context: The Agent can accumulate data collected, analysis results, etc., from periodic tasks into Memory, forming a gradually growing knowledge base. Subsequent tasks can query this historical data for deeper analysis.
- Avoid redundancy and optimize decisions: By checking Memory, the Agent can avoid performing repetitive operations or adjust its behavior based on historical experience. For example, if Memory shows that a certain system component has failed multiple times, the Agent might pay more attention to it during the next check, or even proactively suggest preventive measures.
- Generate history-based reports: Cron tasks can be instructed to "generate a trend analysis report based on the past week's system health check records (retrieved from Memory)."
Example Prompt Snippet and Memory Interaction:
"You are a system administrator assistant. Every day at 2 AM, please check the CPU usage and memory consumption of all critical servers. If any server's CPU usage exceeds 80% twice in a row, or memory consumption exceeds 90%, generate a detailed alert report and record it in my Memory. After each check, please update the latest server health status records in Memory."
In this example, the Agent not only performs a single check but also utilizes Memory to track historical data, thereby making more intelligent alert decisions.
Resource Management and Error Handling
- Resource Consumption: Frequent or complex Cron tasks will increase LLM API call volume, leading to costs. At the same time, frequent tool calls will also consume system resources. When designing automated tasks, it is necessary to balance the frequency and complexity of tasks with resource consumption.
- Error Handling: Although Hermes Agent can self-heal and retry, a clear error reporting mechanism is still important in automated tasks. Instructions like "If the task fails or encounters any errors, please explain in detail and notify me" can be added to the Prompt. Combined with Lesson 05's message gateways, the Agent can send notifications via Telegram or Discord if a task fails.
By combining Cron scheduling with the Agent's intelligent core, external skills, and persistent memory, Hermes Agent can transcend simple scheduled tasks, becoming a truly "ever-vigilant intelligent assistant" that provides continuous value to users.
💻 Hands-on Demonstration
In this section, we will demonstrate how to configure and manage automated tasks using hermes cron commands through several practical scenarios.
Scenario 1: Scheduled Generation and Simulated Sending of Daily Market Summary
We will set up a Cron task for the Agent to automatically generate a market summary based on the latest information every day at 9 AM. To simplify the demonstration, we will not involve actual sending functionality for now (which requires configuring message gateways, see Lesson 05), but instead have the Agent print the summary to the console or logs.
Steps:
Confirm Hermes Agent is running correctly
First, ensure your Hermes Agent is installed and running. If you haven't installed it yet, please refer to Lesson 01.
hermes doctorExpected output should show Agent status as healthy and model configured.
Add Daily Market Summary Cron Task
We will add a task named "Daily Market Summary" that triggers every day at 9 AM. The Agent will be instructed to search for the latest market news and generate a summary.
hermes cron add \ --name "Daily Market Summary" \ --schedule "0 9 * * *" \ --prompt "You are a professional financial analyst. Please use your web_search skill to retrieve today's latest global stock market news and key economic indicators. Then, based on this information, generate a concise daily market summary report, focusing on the potential impact on the technology sector. The report should include a title, key takeaways, and a brief analysis. Finally, simulate sending this report to me, please output the final report content directly."--name "Daily Market Summary": Task name.--schedule "0 9 * * *": Executes daily at 9:00 AM.--prompt "...": Specific instructions for the Agent. Here we explicitly request the use of theweb_searchskill and specify the output format.
Expected output:
Cron job 'Daily Market Summary' added successfully with ID: <some-uuid>Please note
<some-uuid>, this is the unique ID for the task.View Cron Task List
hermes cron listExpected output (similar to):
ID Name Schedule Status Last Run Next Run ------------------------------------ --------------------- ---------- -------- --------------------- --------------------- <some-uuid> Daily Market Summary 0 9 * * * Enabled Never YYYY-MM-DD 09:00:00You can see the task's ID, name, schedule, status, last run time, and next run time.
(Optional) Disable or Delete Task
If you want to temporarily stop a task, you can use the
disablecommand:hermes cron disable <some-uuid>Expected output:
Cron job <some-uuid> disabled successfully.View the list again, and the status will change to
Disabled.hermes cron listOutput:
ID Name Schedule Status Last Run Next Run ------------------------------------ --------------------- ---------- --------- --------------------- --------------------- <some-uuid> Daily Market Summary 0 9 * * * Disabled Never YYYY-MM-DD 09:00:00To re-enable, use the
enablecommand:hermes cron enable <some-uuid>Expected output:
Cron job <some-uuid> enabled successfully.After the demonstration, to avoid unnecessary triggers, we will delete this task:
hermes cron delete <some-uuid>Expected output:
Cron job <some-uuid> deleted successfully.
Scenario 2: Periodic System Health Check and Anomaly Report (Simulated)
In this scenario, we will set up a Cron task that runs hourly, simulating the Agent checking system health. If the Agent "discovers" an anomaly during the check, it will generate a report. Since we don't have a real system monitoring Skill, we will use the Prompt to simulate the Agent's checking logic and result judgment.
Steps:
Add Hourly Health Check Cron Task
We will create a task named "Hourly System Health Check" that executes once every hour. The Prompt will guide the Agent to simulate the check and generate a report based on the simulated results.
hermes cron add \ --name "Hourly System Health Check" \ --schedule "0 * * * *" \ --prompt "You are a system health monitoring assistant. Hourly, please simulate performing a system health check. During the check, assume you discover 'Web Server (Nginx) service has stopped'. Immediately generate a detailed alert report, explaining the problem, possible causes, and initial recommendations. The report should include a title, problem discovered, severity (High), possible causes, and initial recommendations. Output the report content directly."--name "Hourly System Health Check": Task name.--schedule "0 * * * *": Executes once at the 0th minute of every hour.--prompt "...": Simulates the Agent discovering a problem and generating a report.
Expected output:
Cron job 'Hourly System Health Check' added successfully with ID: <another-uuid>Note
<another-uuid>.View Cron Task List
hermes cron listExpected output (similar to):
ID Name Schedule Status Last Run Next Run ------------------------------------ ----------------------------- ---------- -------- --------------------- --------------------- <another-uuid> Hourly System Health Check 0 * * * * Enabled Never YYYY-MM-DD HH:00:00(Simulated) Observe Agent Executing Task and Outputting Results
Since Cron tasks are time-triggered, we cannot see the output immediately. However, during actual runtime, when the scheduled time arrives, Hermes Agent will be activated and will think and generate content according to the Prompt. You can observe the Agent's operational logs or wait for the next trigger time.
If the Agent starts normally and processes this Cron task, you will see output similar to the following in the Agent's operational logs (this depends on your Agent configuration and LLM model behavior):
[AGENT] Received cron task 'Hourly System Health Check' with prompt: "You are a system health monitoring assistant. Hourly, please simulate performing a system health check. During the check, assume you discover 'Web Server (Nginx) service has stopped'. Immediately generate a detailed alert report