Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 278
Harshit Laddha Avatar asked Jun 09 '14 10:06

Harshit Laddha


1 Answers

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
like image 137
Andreas Kalin Avatar answered Sep 28 '22 01:09

Andreas Kalin