简体   繁体   English

如何在 shell 脚本中进行异步函数调用

[英]How to make asynchronous function calls in shell scripts

I have a collection of curl commands to be executed by a shell script.我有一组要由 shell 脚本执行的 curl 命令。 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现在我想要的是所有这些命令都必须以固​​定的时间间隔执行(每个 curl url 都不同)所以我想要做的是异步调用

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.启动 5 个计时器,一个 120 秒,2 个 30 秒,3 个 3000 秒等,然后一旦它们完成,我想触发附加到每个超时的处理程序函数的执行。 I can do this in javascript and nodejs easily as they are event driven programming language.我可以在 javascript 和 nodejs 中轻松地做到这一点,因为它们是事件驱动的编程语言。 But i have little knowledge about shell scripting.但我对 shell 脚本知之甚少。 So, how else can i implement this or hotto make such asynchronous calls in the shell script?那么,我还能如何在 shell 脚本中实现这个或 hotto 进行这样的异步调用? 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. &&这里的意思是如果前一件事没有错误地完成,就做下一件事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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