简体   繁体   中英

How to make asynchronous function calls in shell scripts

I have a collection of curl commands to be executed by a shell script. Now what i want is all these commands have to be executed at a regular interval of time ( which is different for every curl url ) so what i want to do is make asynchronous calls to

wait [sec]

command and execute different functions for different wait periods like

start 5 timers one for 120s, 2 for 30s, 3 for 3000s etc. and then as soon as they get completed i want to trigger the execution of the handler function attached to every timeout. I can do this in javascript and nodejs easily as they are event driven programming language. But i have little knowledge about shell scripting. So, how else can i implement this or hotto make such asynchronous calls in the shell script? I dont know if i am clear enough, what other details should i mention if i am not?

Something to experiment with:

delayed_ajax() {
  local url=$1
  local callback=$2
  local seconds=$3

  sleep $seconds
  curl -s "$url" | "$callback"
}

my_handler() {
  # Read from stdin and do something.
  # E.g. just append to a file:
  cat >> /tmp/some_file.txt
}

for delay in 120 30 30 3000 3000; do
  delayed_ajax http://www.example.com/api/something my_handler $delay &
done

You can also use the & symbol to put this task into the background:

sleep 14 && wget http://yoursitehere.com &
sleep 18 && wget http://yoursitehere.com &
sleep 44 && wget http://yoursitehere.com &

This creates a background task that sleeps for a fixed amount of time, then runs the command. It doesn't wait for each of the tasks to finish.

&& here means that if the previous thing completes without an error, do the next thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM