在 Linux 系统中,有多种方法可以高效地处理批量多任务。以下是一些常用的方法和技术:
command1 & command2 & command3 & wait
&
将命令放入后台执行,wait
等待所有后台任务完成
for item in list; do
process "$item" &
done
wait
GNU Parallel 是专门为并行处理设计的强大工具:
# 基本用法
parallel command ::: arg1 arg2 arg3
# 从文件读取输入
parallel -a file.txt command
# 控制并行度
parallel -j 4 command ::: args # 最多4个并行任务
# 复杂示例:处理多个文件
find . -name "*.log" | parallel -j 8 gzip {}
# 基本并行处理
find . -type f -print0 | xargs -0 -P 4 -n 1 process_file
# 参数说明:
# -P 4: 并行度4
# -n 1: 每次传递1个参数
# -0: 处理含空格/特殊字符的文件名
make -j 8 # 使用8个并行任务
# 生产者
for task in tasks; do
redis-cli RPUSH task_queue "$task"
done
# 消费者 (多个并行运行)
while true; do
task=$(redis-cli LPOP task_queue)
[ -z "$task" ] && break
process "$task"
done
对于大规模任务,可以使用集群管理系统:
# SGE 示例
qsub -t 1-100 -tc 10 job_script.sh # 提交100个任务,最多并行10个
资源监控:并行时监控系统资源 (CPU, 内存, IO)
watch -n 1 'uptime; free -h; iostat -xz 1 1'
错误处理:确保捕获和处理子任务失败
parallel 'process {} || echo "Failed: {}"' ::: args
日志分离:为每个任务生成独立日志
parallel --results outdir/ command ::: args
负载均衡:根据任务复杂度调整并行度
考虑使用:对于复杂场景,可以考虑更专业的工具如 Airflow、Luigi 或 Celery
选择哪种方法取决于任务规模、复杂性以及系统资源情况。对于简单任务,Shell 脚本或 Parallel 通常足够;对于大规模生产环境,可能需要更专业的任务队列系统。