在Linux中设置批处理(batch)任务的并发执行有多种方法,下面介绍几种常见的方式:
GNU Parallel 是专门为并行执行命令设计的强大工具:
# 安装
sudo apt-get install parallel # Debian/Ubuntu
sudo yum install parallel # CentOS/RHEL
# 基本用法
parallel -j 4 < commands.txt # 使用4个并发执行commands.txt中的命令
# 示例:并发处理多个文件
ls *.log | parallel -j 8 "gzip {}"
# 使用4个并发进程处理文件
find . -name "*.txt" | xargs -P 4 -I {} sh -c 'process_file "{}"'
# 示例:并发下载多个URL
cat urls.txt | xargs -P 8 -n 1 wget -q
# 启动多个后台进程
command1 &
command2 &
command3 &
# 等待所有后台进程完成
wait
如果使用Makefile管理任务:
make -j 4 all # 使用4个并发任务
#!/bin/bash
MAX_CONCURRENT=5
count=0
for item in $(cat list.txt); do
((count++))
( process_item "$item" ) &
if (( count % MAX_CONCURRENT == 0 )); then
wait # 等待一批任务完成
fi
done
wait # 等待剩余任务完成
# 在tmux中创建多个窗口并行执行
tmux new-session -d -s batch_job 'command1'
tmux new-window -t batch_job:1 'command2'
tmux new-window -t batch_job:2 'command3'
您可以根据具体需求选择最适合的方法来实现批处理任务的并发执行。