DEV Community

steven x
steven x

Posted on

FastClaw in Action: Automate Your Work with Cron Jobs

In daily work, we often need to handle various repetitive tasks: generating reports daily, backing up data on schedule, checking system status periodically, etc. FastClaw has a powerful built-in Cron scheduling system that makes these repetitive tasks simple and automated.

What is Cron?

Cron is a classic time-based job scheduler that uses cron expressions to define task execution times. FastClaw brings this concept into the AI Agent world, allowing you to define and manage scheduled tasks using natural language.

Cron Expression Basics

FastClaw uses the standard 5-field cron expression:

┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-7, 0 and 7 are Sunday)
│ │ │ │ │
* * * * *
Enter fullscreen mode Exit fullscreen mode

Common Cron Expression Examples

Expression Meaning Use Case
*/5 * * * * Every 5 minutes Real-time monitoring, data collection
0 * * * * Every hour on the hour Hourly reports, resource cleanup
0 9 * * * Daily at 9:00 AM Morning reports, daily generation
0 9,18 * * * Daily at 9 AM and 6 PM Morning and evening reports
0 9 * * 1-5 Weekdays at 9:00 AM Weekday daily reports
30 4 * * 0 Sunday at 4:30 AM Weekly reports, backups
0 0 1 * * First day of month Monthly reports
*/15 9-17 * * 1-5 Weekdays 9-17 every 15 min Work hour monitoring

Quick Start

Start Cron Service

FastClaw's Cron service starts with the main service by default:

# Start service (includes Cron service)
python main.py start

# View Cron task list
python main.py cron list
Enter fullscreen mode Exit fullscreen mode

Create Your First Scheduled Task

Create via Web UI

  1. Open http://localhost:8765
  2. Switch to Cron tab
  3. Click New Task
  4. Fill in task information:
    • Task Name: Daily Weather Report
    • Cron Expression: 0 8 * * *
    • Agent: main_agent
    • Command: Query Beijing weather and save to file
  5. Click Save

Create via Configuration File

Edit workspace/data/cron/tasks.json:

{
  "tasks": [
    {
      "name": "Daily Weather Report",
      "cron": "0 8 * * *",
      "agent": "main_agent",
      "session_id": "weather_report",
      "command": "Query Beijing weather and save to workspace/weather_report.txt",
      "enabled": true
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Practical Use Cases

Case 1: Automated Data Backup

Requirement

Automatically backup important data to a specified directory at 2 AM daily.

Implementation

{
  "name": "Daily Data Backup",
  "cron": "0 2 * * *",
  "agent": "main_agent",
  "session_id": "backup_task",
  "command": "Create backup: backup workspace/data directory to workspace/backups/backup_$(date +%Y%m%d).tar.gz",
  "enabled": true
}
Enter fullscreen mode Exit fullscreen mode

Task Execution Process

When FastClaw executes this task, it will:

  1. Trigger cron.triggered event
  2. Agent parses command: "Create backup: backup workspace/data directory to..."
  3. Agent calls run_shell to execute backup command:
   mkdir -p workspace/backups
   tar -czf workspace/backups/backup_$(date +%Y%m%d).tar.gz workspace/data
Enter fullscreen mode Exit fullscreen mode
  1. Save execution result to log

Case 2: Scheduled Work Report Generation

Requirement

Automatically generate work report before end of each workday (6 PM).

Implementation

{
  "name": "Work Report Generation",
  "cron": "0 18 * * 1-5",
  "agent": "main_agent",
  "session_id": "daily_report",
  "command": "Summarize today's work and generate a concise work report, save to workspace/reports/daily_$(date +%Y%m%d).md",
  "enabled": true
}
Enter fullscreen mode Exit fullscreen mode

Task Execution Process

  1. Trigger cron.triggered event
  2. Agent understands task: "Summarize today's work, generate report"
  3. Agent may:
    • Read today's chat logs and work files
    • Analyze work content
    • Generate summary report
    • Save to specified file

Case 3: System Health Check

Requirement

Check system resource usage every 15 minutes, alert if abnormal.

Implementation

{
  "name": "System Health Check",
  "cron": "*/15 * * * *",
  "agent": "main_agent",
  "session_id": "health_check",
  "command": "Check system resources: if CPU > 90% or Memory > 85%, send alert to feishu; otherwise log normal status to workspace/logs/health_$(date +%Y%m%d_%H%M).log",
  "enabled": true
}
Enter fullscreen mode Exit fullscreen mode

Alert Logic

Agent automatically determines whether to alert:

  • Normal state: Resource usage is normal → Log status
  • Alert state: Resource usage too high → Call run_skills("feishu", {...}) to send Feishu message

Case 4: Scheduled News Aggregation

Requirement

Automatically fetch tech news and generate newsletter every morning at 8 AM.

Implementation

{
  "name": "Tech News Morning Brief",
  "cron": "0 8 * * *",
  "agent": "main_agent",
  "session_id": "tech_news",
  "command": "Fetch latest AI/programming tech news, generate newsletter and save to workspace/news/tech_daily_$(date +%Y%m%d).md",
  "enabled": true
}
Enter fullscreen mode Exit fullscreen mode

Execution Steps

  1. run_shell("curl https://news.example.com/tech.rss") - Fetch RSS feed
  2. Parse news content
  3. Generate newsletter format
  4. Save to file

Case 5: Scheduled Database Sync

Requirement

Sync database to backup server every hour.

Implementation

{
  "name": "Database Scheduled Sync",
  "cron": "0 * * * *",
  "agent": "main_agent",
  "session_id": "db_sync",
  "command": "Execute database sync: export local database and sync to remote backup server 192.168.1.100's /backup/db/ directory",
  "enabled": true
}
Enter fullscreen mode Exit fullscreen mode

Sync Script

Agent may execute:

mysqldump -u root -ppassword fastclaw_db > backup.sql
scp backup.sql user@192.168.1.100:/backup/db/
Enter fullscreen mode Exit fullscreen mode

Task Management Commands

View Task List

python main.py cron list
Enter fullscreen mode Exit fullscreen mode

Example output:

Task Name              Cron Expression    Status    Last Run
--------------------------------------------------------------
Daily Weather Report   0 8 * * *         Enabled   2024-01-15 08:00:00
Daily Data Backup      0 2 * * *         Enabled   2024-01-15 02:00:00
Work Report Generation 0 18 * * 1-5      Enabled   2024-01-15 18:00:00
System Health Check    */15 * * * *      Enabled   2024-01-15 10:45:00
Enter fullscreen mode Exit fullscreen mode

Manually Trigger Task

# Execute specified task immediately
python main.py cron run Daily Weather Report

# Execute all tasks immediately
python main.py cron run --all
Enter fullscreen mode Exit fullscreen mode

Enable/Disable Task

# Disable task
python main.py cron disable Daily Weather Report

# Enable task
python main.py cron enable Daily Weather Report
Enter fullscreen mode Exit fullscreen mode

Delete Task

python main.py cron del Daily Weather Report
Enter fullscreen mode Exit fullscreen mode

Task Logs and Monitoring

View Execution Logs

# View recent logs
tail -f workspace/data/cron/logs/fastclaw_cron.log

# View specific task log
cat workspace/data/cron/logs/tasks/Daily\ Weather\ Report.log
Enter fullscreen mode Exit fullscreen mode

Log Format

2024-01-15 08:00:00 [INFO] Task triggered: Daily Weather Report
2024-01-15 08:00:01 [INFO] Executing command: Query Beijing weather and save to workspace/weather_report.txt
2024-01-15 08:00:03 [INFO] Execution result: Success
2024-01-15 08:00:03 [INFO] Execution time: 2.3s
Enter fullscreen mode Exit fullscreen mode

Set Alert Notifications

Configure in workspace/data/settings.json:

{
  "cron": {
    "on_failure": "notify",
    "notification_channel": "feishu",
    "retry_times": 3,
    "retry_interval": 60
  }
}
Enter fullscreen mode Exit fullscreen mode

Advanced Usage

1. Task Dependency Chains

Create dependency chains where one task triggers the next after completion:

{
  "name": "Task A: Data Collection",
  "cron": "0 9 * * *",
  "agent": "main_agent",
  "session_id": "task_a",
  "command": "Collect yesterday's sales data and save to workspace/data/sales_raw.json",
  "enabled": true
},
{
  "name": "Task B: Data Analysis",
  "cron": "0 10 * * *",
  "agent": "main_agent",
  "session_id": "task_b",
  "command": "Read workspace/data/sales_raw.json, perform data analysis and generate report",
  "enabled": true
}
Enter fullscreen mode Exit fullscreen mode

2. Conditional Execution

Use natural language for Agent to autonomously decide whether to execute:

{
  "name": "Smart Backup",
  "cron": "0 2 * * *",
  "agent": "main_agent",
  "session_id": "smart_backup",
  "command": "Check if there were important updates today, if so perform backup; otherwise skip and log: No backup needed today",
  "enabled": true
}
Enter fullscreen mode Exit fullscreen mode

3. Recurring Tasks

Create recurring tasks at intervals:

{
  "name": "Long Task Monitoring",
  "cron": "*/30 * * * *",
  "agent": "main_agent",
  "session_id": "monitor",
  "command": "Check status of previously started build task, if complete send notification and record result",
  "enabled": true
}
Enter fullscreen mode Exit fullscreen mode

4. Context Preservation

Long-running tasks can preserve context across sessions:

{
  "name": "Large File Processing",
  "cron": "0 3 * * *",
  "agent": "main_agent",
  "session_id": "big_file_task",
  "session_persistence": true,
  "command": "Continue processing previously unfinished large file analysis task",
  "enabled": true
}
Enter fullscreen mode Exit fullscreen mode

Best Practices

1. Task Design Principles

  • Single Responsibility: Each task does one thing
  • Idempotency: Tasks can be safely executed multiple times
  • Fast Execution: Avoid long execution times for single tasks
  • Clear Logging: Record sufficient execution info for troubleshooting

2. Time Planning Suggestions

Task Type Recommended Time Reason
Data Backup 2-4 AM Lowest system load
Daily Report 1 hour before end of work Work content is complete
Health Check During work hours Catch issues promptly
Data Sync On the hour Easy to align
Report Generation 8-9 AM Ready before work starts

3. Resource Optimization

  • Stagger Execution: Avoid multiple tasks running simultaneously
  • Merge Tasks: Combine related small tasks
  • Incremental Processing: Prioritize processing incremental data

4. Monitoring and Alerts

  • Critical Tasks: Must set failure alerts
  • Normal Tasks: Log only is sufficient
  • Long-running Tasks: Check progress periodically

Troubleshooting

Task Not Executing

  1. Check if task is enabled: python main.py cron list
  2. Check if Cron service is running: ps aux | grep fastclaw
  3. Check system logs: journalctl -u fastclaw
  4. Verify cron expression is correct

Task Execution Failed

  1. View task log: cat workspace/data/cron/logs/tasks/TaskName.log
  2. Manual execution test: python main.py cron run TaskName
  3. Check Agent configuration: vim workspace/data/agents/main_agent/metadata.json
  4. Confirm LLM API is available

Task Execution Timeout

Default task timeout is 5 minutes. Adjust in configuration if longer execution is needed:

{
  "cron": {
    "task_timeout": 600
  }
}
Enter fullscreen mode Exit fullscreen mode

Summary

FastClaw's Cron scheduled task system makes workflow automation simple and powerful. Through natural language interaction, you can:

  1. Easy Creation: Describe tasks in natural language, no coding required
  2. Flexible Scheduling: Support various cron expressions for complex timing needs
  3. Smart Execution: Agent autonomously decides, can handle complex logic
  4. Complete Logging: Detailed execution records for tracking and troubleshooting
  5. Alert Notifications: Automatic notifications on task failure for prompt handling

Whether you're a personal user or enterprise user, FastClaw's Cron functionality enables workflow automation, letting AI handle repetitive tasks so you can focus on more valuable work.

Related Resources

Start your automation journey today!

Top comments (0)