Skip to content

Instantly share code, notes, and snippets.

@alexander-matz
Last active February 11, 2022 12:41
Show Gist options
  • Save alexander-matz/78b8b2dab8418d811a4f832db1936401 to your computer and use it in GitHub Desktop.
Save alexander-matz/78b8b2dab8418d811a4f832db1936401 to your computer and use it in GitHub Desktop.
dead simple pure-bash "job scheduler" with configurable number of background processes
#!/bin/bash
run-async() {
local joblist=($(jobs -p))
while (( ${#joblist[*]} >= 4 )); do # set 4 to the maximum number of jobs you want
sleep 0.1
joblist=($(jobs -p))
done
if [[ $# -eq 0 ]]; then # start shell with provided input if no arguments
local code="$(</dev/stdin)"
bash -c "$code" &
else # otherwise launch arguments as command
"$@" &
fi
}
# example (arguments)
for i in {1..8}; do
run-async bash -c "echo starting $i; sleep 3; echo stopping $i"
done
# example (stdin)
for i in {9..16}; do
run-async <<-EOF
echo starting $i
sleep 3
echo stopping $i"
EOF
done
wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment