Shell: is it possible to delay a command without using `sleep`?
With bash
builtins, you can do:
coproc read -t 10 && wait "$!" || true
To sleep for 10 seconds without using sleep
. The coproc
is to make so that read
's stdin is a pipe where nothing will ever come out from. || true
is because wait
's exit status will reflect a SIGALRM delivery which would cause the shell to exit if the errexit
option is set.
In other shells:
mksh
and ksh93
have sleep
built-in, no point in using anything else there (though they both also support read -t
).
zsh
also supports read -t
, but also has a builtin wrapper around select()
, so you can also use:
zmodload zsh/zselect
zselect -t 1000 # centiseconds
If what you want is schedule things to be run from an interactive shell session, see also the zsh/sched
module in zsh
.
You have alternatives to sleep
: They are at
and cron
. Contrary to sleep
these need you to provide the time at which you need them to run.
Make sure the
atd
service is running by executingservice atd status
.
Now let's say the date is 11:17 am UTC; if you need to execute a command at 11:25 UTC, the syntax is:echo "This is a test" | at 11:25
.
Now keep in mind thatatd
by default will not be logging the completion of the jobs. For more refer this link. It's better that your application has its own logging.You can schedule jobs in
cron
, for more refer :man cron
to see its options orcrontab -e
to add new jobs./var/log/cron
can be checked for the info on execution on jobs.
FYI sleep system call
suspends the current execution and schedules it w.r.t. the argument passed to it.
EDIT:
As @Gaius mentioned , you can also add minutes time to at
command.But lets say time is 12:30:30
and now you ran the scheduler with now +1 minutes
. Even though 1 minute, which translates to 60 seconds was specified , the at
doesn't really wait till 12:31:30
to execute the job, rather it executes the job at 12:31:00
. The time-units can be minutes, hours, days, or weeks
. For more refer man at
e.g: echo "ls" | at now +1 minutes
Some other ideas.
top -d10 -n2 >/dev/null
vmstat 10 2 >/dev/null
sar 10 1 >/dev/null
timeout 10s tail -f /dev/null