bash 如何在 shell 脚本中进行异步函数调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24118224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make asynchronous function calls in shell scripts
提问by Harshit Laddha
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
我有一组要由 shell 脚本执行的 curl 命令。现在我想要的是所有这些命令都必须以固定的时间间隔执行(每个 curl url 都不同)所以我想做的是异步调用
wait [sec]
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?
启动 5 个计时器,一个 120 秒,2 个 30 秒,3 个 3000 秒等,然后一旦它们完成,我想触发附加到每个超时的处理程序函数的执行。我可以在 javascript 和 nodejs 中轻松地做到这一点,因为它们是事件驱动的编程语言。但我对 shell 脚本知之甚少。那么,我还能如何在 shell 脚本中实现这个或 hotto 进行这样的异步调用?我不知道我是否足够清楚,如果我不清楚,我还应该提到哪些细节?
采纳答案by Andreas Kalin
Something to experiment with:
可以尝试的东西:
delayed_ajax() {
local url=
local callback=
local seconds=
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
回答by Andre Lewis
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.
&&
这里的意思是如果前一件事没有错误地完成,就做下一件事。