简体   繁体   中英

How to defer a function execution in bash?

I would like to defer a function execution. My current approach is something like this:

do_afterwards () {
    sleep 2
    echo "do something later"
}

do_afterwards &
start_my_webserver & start_monitoring_webserver

start_my_webserver & start_monitoring_webserver will run in the foreground of my terminal and "block it". I want to run do_afterwards after my Webservers started. Currently I am doing that simply with a dummy wait. How can I do this smarter?

If the question is how to start both do_afterwards and start_monitoring_webserver simultaneously after start_my_webserver finished, then the following could work:

do_afterwards () {
    echo "do something later"
}

start_my_webserver () {
  echo "starting"
  sleep 2
  echo "started"
}

start_monitoring_webserver () {
  echo "monitoring"
  sleep 2
  echo "monitoring"
  sleep 2
  echo "monitoring"
}

post_start() {
  do_afterwards &
  start_monitoring_webserver
}

start_my_webserver && post_start

Result:

starting
started
monitoring
do something later
monitoring
monitoring

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