[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Deterministic delays in POSIX shell scripts (Was: Re: notify via virtual terminal available packages)



Hello,

On Thu, Sep 24, 2020 at 08:49:07AM -0600, Charles Curley wrote:
> On Thu, 24 Sep 2020 10:38:55 -0400
> Greg Wooledge <wooledg@eeg.ccf.org> wrote:
> > So you're just doing "sleep 1" every time.
> 
> Ah, thank you. Yup. Which is weird, because it worked when I first
> wrote that many years ago.

In cron scripts where I want a "random" delay, I actually tend to
not really want it to be random, but just different for that host as
opposed to other hosts, otherwise deterministic. I like it if the
delay is the same every time on that host as long as it is a
different delay on different hosts.

So what I tend to do is something like:

    sleep $(( $(printf %d "0x$(hostid)") % 60 ))m; /some/command

which will sleep for some amount of time between 0 and 59 minutes,
the same amount every time, but different on different hosts.

(Obviously change the "60" and the "m" to different values for
different things, like you might want "1440" and "m" for minutes in
a day.)

Note that in a file parsed by cron you do need to escape both the
'%' (like '\%').

The printf is needed to turn the hexadecimal value from the "hostid"
command into a decimal number. Is there a way to do that with pure
shell internals that isn't very verbose?

"hostid" tends to return a hexadecimal representation of the first
IPv4 address (but isn't guaranteed to). On a systemd system one
could instead use /etc/machine-id. On Linux there is also
/proc/sys/kernel/random/boot_id (but needs dashes removed).

Systemd timers can do this sort of thing themselves, so no need
there for this sort of scripting.

> But I will move toward more use of unattended-upgrades, which
> handles the original problem differently.

Yup, I use apticron and unattended-upgrades for solving these
problems these days.

Cheers,
Andy

-- 
https://bitfolk.com/ -- No-nonsense VPS hosting

Please consider the environment before reading this e-mail.
 — John Levine


Reply to: