关于 timeout-prevention
timeout-prevention 是一项 Claude Code 技能,旨在降低长时间或大规模操作发生超时的风险。它介绍分批处理、进度检查点、后台执行、显式超时设置和恢复模式。
主要功能
- 01将任务拆分为批次
- 02保存可恢复检查点
- 03在后台运行命令
- 04跟踪阶段性进度
- 05设置明确的命令超时
- 06限制并行执行数量
适用场景
- 01处理大量文件
- 02克隆多个代码仓库
- 03下载多个文件
- 04恢复中断的工作流
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jackspace/ claudeskillz --skill timeout-prevention安装后在 Claude Code 中输入/timeout-prevention确认已加载。
附带文件SKILL.json
详细介绍
超时预防技能
通过将长时间运行的操作拆分为易于管理的小块,并配合进度跟踪和恢复机制,运用专家策略防止 Claude Code 请求超时。
何时使用此技能
适用于:
- 执行批量操作(100 个以上的文件、仓库等)
- 运行耗时较长的命令(超过 60 秒)
- 处理大型数据集
- 按顺序下载多个文件
- 执行复杂的多步骤工作流
- 使用响应缓慢的外部 API
- 任何有超时风险的操作
了解超时限制
Claude Code 超时行为
- 默认工具超时时间:120 秒(2 分钟)
- 请求超时:整个响应周期
- 导致超时的原因:
- 长时间运行的 bash 命令
- 大型文件操作
- 按顺序处理大量项目
- 未正确设置超时时间的网络操作
- 没有进度反馈的阻塞操作
核心预防策略
1. 任务分块
将大型操作拆分为较小的批次:
# ❌ BAD: Process all 1000 files at once
for file in $(find . -name "*.txt"); do
process_file "$file"
done
# ✅ GOOD: Process in batches of 10
find . -name "*.txt" | head -10 | while read file; do
process_file "$file"
done
# Then process next 10, etc.
2. 进度检查点
保存进度,以便中断后恢复:
# Create checkpoint file
CHECKPOINT_FILE="progress.txt"
# Save completed items
echo "completed_item_1" >> "$CHECKPOINT_FILE"
# Skip already completed items
if grep -q "completed_item_1" "$CHECKPOINT_FILE"; then
echo "Skipping already processed item"
fi
3. 后台进程
在后台运行耗时较长的操作:
# Start long-running process in background
long_command > output.log 2>&1 &
echo $! > pid.txt
# Check status later
if ps -p $(cat pid.txt) > /dev/null; then
echo "Still running"
else
echo "Completed"
cat output.log
fi
4. 增量处理
逐步处理并报告结果:
# Process items one at a time with status updates
TOTAL=100
for i in $(seq 1 10); do # First 10 of 100
process_item $i
echo "Progress: $i/$TOTAL"
done
# Continue with next 10 in subsequent calls
5. 超时配置
为命令设置明确的超时时间:
# Use timeout command
timeout 60s long_command || echo "Command timed out"
# Set timeout in tool calls
yt-dlp --socket-timeout 30 "URL"
git clone --depth 1 --timeout 60 "URL"
实用模式
模式 1:批量文件处理
# Define batch size
BATCH_SIZE=10
OFFSET=${1:-0} # Accept offset as parameter
# Process batch
find . -name "*.jpg" | tail -n +$((OFFSET + 1)) | head -$BATCH_SIZE | while read file; do
convert "$file" -resize 800x600 "thumbnails/$(basename $file)"
echo "Processed: $file"
done
# Report next offset
NEXT_OFFSET=$((OFFSET + BATCH_SIZE))
echo "Next batch: Run with offset $NEXT_OFFSET"
用法:
# First batch
./process.sh 0
# Next batch
./process.sh 10
# Continue...
./process.sh 20
模式 2:带检查点的仓库克隆
#!/bin/bash
REPOS_FILE="repos.txt"
CHECKPOINT="downloaded.txt"
# Read repos, skip already downloaded
while read repo; do
# Check if already downloaded
if grep -q "$repo" "$CHECKPOINT" 2>/dev/null; then
echo "✓ Skipping $repo (already downloaded)"
continue
fi
# Clone with timeout
echo "Downloading $repo..."
if timeout 60s git clone --depth 1 "$repo" 2>/dev/null; then
echo "$repo" >> "$CHECKPOINT"
echo "✓ Downloaded $repo"
else
echo "✗ Failed: $repo"
fi
done < <(head -5 "$REPOS_FILE") # Only 5 at a time
echo "Processed 5 repos. Check $CHECKPOINT for status."
模式 3:跟踪进度的下载
#!/bin/bash
URLS_FILE="urls.txt"
PROGRESS_FILE="download_progress.json"
# Initialize progress
[ ! -f "$PROGRESS_FILE" ] && echo '{"completed": 0, "total": 0}' > "$PROGRESS_FILE"
# Get current progress
COMPLETED=$(jq -r '.completed' "$PROGRESS_FILE")
TOTAL=$(wc -l < "$URLS_FILE")
# Download next batch (5 at a time)
BATCH_SIZE=5
tail -n +$((COMPLETED + 1)) "$URLS_FILE" | head -$BATCH_SIZE | while read url; do
echo "Downloading: $url"
if yt-dlp --socket-timeout 30 "$url"; then
COMPLETED=$((COMPLETED + 1))
echo "{\"completed\": $COMPLETED, \"total\": $TOTAL}" > "$PROGRESS_FILE"
fi
done
# Report progress
COMPLETED=$(jq -r '.completed' "$PROGRESS_FILE")
echo "Progress: $COMPLETED/$TOTAL"
[ $COMPLETED -lt $TOTAL ] && echo "Run again to continue."
模式 4:带速率限制的并行执行
#!/bin/bash
MAX_PARALLEL=3
COUNT=0
for item in $(seq 1 15); do
# Start background job
(
process_item $item
echo "Completed: $item"
) &
COUNT=$((COUNT + 1))
# Wait when reaching max parallel
if [ $COUNT -ge $MAX_PARALLEL ]; then
wait -n # Wait for any job to finish
COUNT=$((COUNT - 1))
fi
# Rate limiting
sleep 0.5
done
# Wait for remaining jobs
wait
echo "All items processed"
模式 5:可恢复的状态机
#!/bin/bash
STATE_FILE="workflow_state.txt"
# Read current state (default: START)
STATE=$(cat "$STATE_FILE" 2>/dev/null || echo "START")
case $STATE in
START)
echo "Phase 1: Initialization"
initialize_project
echo "PHASE1" > "$STATE_FILE"
echo "Run again to continue to Phase 2"
;;
PHASE1)
echo "Phase 2: Processing (Batch 1 of 3)"
process_batch_1
echo "PHASE2" > "$STATE_FILE"
echo "Run again for Phase 3"
;;
PHASE2)
echo "Phase 3: Processing (Batch 2 of 3)"
process_batch_2
echo "PHASE3" > "$STATE_FILE"
echo "Run again for Phase 4"
;;
PHASE3)
echo "Phase 4: Processing (Batch 3 of 3)"
process_batch_3
echo "PHASE4" > "$STATE_FILE"
echo "Run again for finalization"
;;
PHASE4)
echo "Phase 5: Finalization"
finalize_project
echo "COMPLETE" > "$STATE_FILE"
echo "Workflow complete!"
;;
COMPLETE)
echo "Workflow already completed"
;;
esac
命令优化
优化 Bash 命令
# ❌ SLOW: Multiple commands sequentially
git clone repo1
git clone repo2
git clone repo3
# ✅ FAST: Parallel with wait
git clone repo1 &
git clone repo2 &
git clone repo3 &
wait
优化文件操作
# ❌ SLOW: Process one file at a time
for file in *.txt; do
cat "$file" | process > "output/$file"
done
# ✅ FAST: Parallel processing
for file in *.txt; do
cat "$file" | process > "output/$file" &
done
wait
优化网络调用
# ❌ SLOW: Sequential API calls
for id in {1..100}; do
curl "https://api.example.com/item/$id"
done
# ✅ FAST: Batch API call
curl "https://api.example.com/items?ids=1,2,3,4,5"
Claude Code 集成
策略 1:多轮工作流
不要一次执行长时间操作,而是拆分为多轮:
第 1 轮:
Process first 10 repositories and report progress
第 2 轮:
Process next 10 repositories (11-20)
第 3 轮:
Process final batch and generate report
策略 2:状态检查模式
# Turn 1: Start background process
./long_operation.sh > output.log 2>&1 &
echo $! > pid.txt
echo "Started background process"
# Turn 2: Check status
if ps -p $(cat pid.txt) > /dev/null; then
echo "Still running... Check again"
tail -20 output.log
else
echo "Completed!"
cat output.log
fi
策略 3:增量结果
逐步报告部分结果:
echo "=== Batch 1 Results ==="
process_batch_1
echo ""
echo "=== Batch 2 Results ==="
process_batch_2
错误处理
优雅降级
# Try operation with timeout, fallback if fails
if timeout 30s expensive_operation; then
echo "Operation completed"
else
echo "Operation timed out, using cached result"
cat cached_result.txt
fi
重试逻辑
MAX_RETRIES=3
RETRY_COUNT=0
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
if timeout 60s risky_operation; then
echo "Success!"
break
else
RETRY_COUNT=$((RETRY_COUNT + 1))
echo "Attempt $RETRY_COUNT failed, retrying..."
sleep 5
fi
done
最佳实践
✅ 应该做
- 拆分大型操作:每次处理 5-10 个项目
- 保存进度:使用检查点文件
- 逐步报告:边处理边展示结果
- 设置超时:明确设定超时时间
- 合理并行:最多同时执行 3-5 个操作
- 启用恢复:确保操作可以恢复
- 监控进度:显示完成百分比
- 将耗时任务放在后台:使用
&执行异步操作
❌ 不应该做
- 不要一次处理所有内容:对大型数据集分批处理
- 不要无限阻塞:始终设置超时时间
- 不要忽略状态:在各次运行之间保存进度
- 不要不报告进展:定期报告进度
- 不要无限重试:限制重试次数
- 不要过度并行:限制并发操作数量
- 不要假设操作成功:始终检查返回码
- 不要跳过清理:清理临时文件
常见场景
场景 1:下载 100 个 YouTube 视频
# DON'T do this (will timeout)
yt-dlp -a urls.txt # 100 URLs
# DO this instead
head -5 urls.txt | yt-dlp -a -
# Then process next 5 in another turn
场景 2:克隆 50 个仓库
# DON'T
for repo in $(cat repos.txt); do
git clone $repo
done
# DO
head -5 repos.txt | while read repo; do
timeout 60s git clone --depth 1 $repo
done
# Continue with tail -n +6 in next turn
场景 3:处理 1000 张图片
# DON'T
for img in *.jpg; do
convert $img processed/$img
done
# DO
find . -name "*.jpg" | head -20 | xargs -P 4 -I {} convert {} processed/{}
# Process next 20 in subsequent turn
监控和调试
跟踪执行时间
start_time=$(date +%s)
# ... operations ...
end_time=$(date +%s)
duration=$((end_time - start_time))
echo "Duration: ${duration}s"
记录所有内容
LOG_FILE="operation.log"
{
echo "Started at $(date)"
perform_operations
echo "Completed at $(date)"
} | tee -a "$LOG_FILE"
进度指示器
TOTAL=100
for i in $(seq 1 10); do
process_item $i
echo -ne "Progress: $i/$TOTAL\r"
done
echo ""
恢复策略
基于检查点的恢复
# Check last successful checkpoint
LAST_CHECKPOINT=$(cat .checkpoint 2>/dev/null || echo 0)
echo "Resuming from item $LAST_CHECKPOINT"
# Continue from checkpoint
for i in $(seq $((LAST_CHECKPOINT + 1)) $((LAST_CHECKPOINT + 10))); do
process_item $i && echo $i > .checkpoint
done
类似事务的操作
# Create temporary workspace
TEMP_DIR=$(mktemp -d)
trap "rm -rf $TEMP_DIR" EXIT
# Work in temp, only commit on success
cd $TEMP_DIR
perform_operations
if [ $? -eq 0 ]; then
mv $TEMP_DIR/results ~/final/
fi
版本:1.0.0 最后更新:2025-11-07 核心原则:将长时间运行的操作拆分为易于管理的小块,并跟踪进度以便恢复
评论
支持 Markdown