cron-polling-anti-patterns.md 2.99 KB

Cron Polling Anti-Patterns for VisualAgent

Problem

When running as a cron job that monitors a command directory, it's tempting to repeatedly check the directory in a tight loop, hoping new commands will appear. This wastes tool calls, produces no new information, and can trigger rate limits.

Error Signature (What NOT to do)

> ls -la /sdcard/VisualAgent/commands/  → "DIR_EMPTY"
> ls -la /sdcard/VisualAgent/commands/  → "DIR_EMPTY"
> ls -la /sdcard/VisualAgent/commands/  → "DIR_EMPTY"
> ls -la /sdcard/VisualAgent/commands/  → "DIR_EMPTY"
# ... 15 more identical checks ...

Each check is a separate terminal tool call that returns the same result. This is pure waste.

Correct Approach

Single Check with find

Use a single command that lists all matching files:

# One command checks everything
su -c "find /sdcard/VisualAgent/commands/ -name '*.json' -type f 2>/dev/null"

If the output is empty → respond [SILENT] and stop.

If files are found → process them.

Batch Processing

If multiple command files exist, process them all in one cron run rather than leaving some for the next:

# List all files at once
FILES=$(su -c "find /sdcard/VisualAgent/commands/ -name '*.json' -type f 2>/dev/null")

if [ -z "$FILES" ]; then
    echo "[SILENT]"
    exit 0
fi

# Process each file
for f in $FILES; do
    echo "Processing: $f"
    # ... read, execute, write result ...
done

Why This Matters

  1. Tool call budget — Each terminal call consumes resources. A cron job that loops 20 times checking an empty directory is 20x more expensive than one check.
  2. No new information — The directory state doesn't change between checks unless an external actor drops a file. Repeated checks of an empty directory are guaranteed to return the same result.
  3. Rate limiting — Some systems rate-limit tool calls. Excessive polling may trigger throttling.
  4. Log noise — Each check generates output that must be processed and stored.

When to Check Again

The cron job will run again at its next scheduled interval. That's when to check again. Within a single run:

  • Check once
  • If empty → [SILENT] → done
  • If files found → process all → done

Exception: Long-Running Processes

If a command takes significant time (e.g., waiting for an app to load), the agent may need to poll for state changes. In that case:

  1. Execute the command
  2. Check for the expected outcome (e.g., UI element appearing)
  3. Use a small number of retries with delays, not infinite loops
  4. Set a maximum retry count and timeout
# Poll for a result with max retries
MAX_RETRIES=5
for i in $(seq 1 $MAX_RETRIES); do
    if check_condition; then
        break
    fi
    sleep 2
done

Summary

Pattern Result
Repeated ls in a loop ❌ Wasteful, no new info
Single find then decide ✅ Efficient, correct
Process all files in one run ✅ Efficient, correct
[SILENT] when empty ✅ Correct for cron jobs