sábado, 29 de octubre de 2016

Programar un sleep con tiempo aleatorio

Comparto una función que aunque simple, considero interesante incluirla en la librería personal de funciones bash.
Básicamente hace esperar un tiempo aleatorio a un script, útil para programar reintentos. Variando el valor de la variable RandomSleep se puede ajustar el tiempo máximo de espera.
random_sleep()
{
    RandomSleep=1800
    if [ $RandomSleep -eq 0 ]; then
        return
    fi
    if [ -z "$RANDOM" ] ; then
        # A fix for shells that do not have this bash feature.
        RANDOM=$(( $(dd if=/dev/urandom bs=2 count=1 2> /dev/null | cksum | cut -d' ' -f1) % 32767 ))
    fi
    TIME=$(($RANDOM % $RandomSleep))
    echo "sleeping for $TIME seconds"
    sleep $TIME
}

No hay comentarios:

Publicar un comentario