How to run a command in the background with a delay?

( sleep 300 ; echo "80" > /sys/class/leds/blue/brightness ) &

That way your script continues, or you restore control immediately, while a new background task of the script starts, with two commands: sleep, and echo.

The common error is trying to give either sleep or echo or both the & which will not work as intended. Launching a series of commands in () though spawns them in a separate shell process, which you can then send whole into background with &.


To that wit, where I found it actively useful. In an embedded device I develop there's the main application that works with a watchdog. If it fails in a way that triggers the watchdog reset soon after startup, repeatedly, it's hard to fix remotely as the period between the OS start and the reset is quite short, not enough to ssh in, and block the app startup. So I need a way to determine the system restarted so fast and introduce a delay if it did, to give myself time to fix it manually.

 [ -f /tmp/startdelay ] && sleep 30
 touch /tmp/startdelay
 ( sleep 30 ; rm /tmp/startdelay ) &
 [ -f /tmp/noautostart ] && exit 0
 start_app

If I log in and perform touch /tmp/noautostart the main app won't start. If the watchdog kicks in, rm /tmp/startdelay won't be performed and the next time the system starts, it will give me extra 30s to stop it. Otherwise restart will be quick, without delay.


use the at command

echo "echo \"80\" > /sys/class/leds/blue/brightness" | at now + 5 min

that will run in the background


If you want something to run in 5 minutes, but the rest of your program to continue (or finish), you need to background the sleep as well:

#!/bin/bash

runWithDelay () {
    sleep $1;
    shift;
    "${@}";
}

runWithDelay 3 echo world &
echo hello    

This will print hello and then 3 seconds later (after the main program has exited), print world.

The important part is the & to fork the function execution into the background.

Tags:

Linux

Android