2

Need run a shell script once a day at random time. (so once every day between 00:00-23:59).

I know the sleep command, and the cron too, but

  • the cron has not random times
  • and the sleep solution - not very nice - my idea is launch the script every midnight and sleep random time at the start of the script.

Is here something more elegant?

Undo
  • 25,519
  • 37
  • 106
  • 129
clt60
  • 62,119
  • 17
  • 107
  • 194

5 Answers5

10

If you have the at command, you can combinte the cron and the at.

Run from a cron every midnight the next script:

#!/bin/bash
script="/tmp/script.sh"      #insert the path to your script here
min=$(( 24 * 60 ))
rmin=$(( $RANDOM % $min ))
at -f "$script" now+${rmin}min

The above will run the at command every midnight and will execute your script at random time . You should check your crontab how often is the atrun command started. (The atrun runs the commands stored with the at)

The main benefit in comparison with the sleep method: this "survives" the system reboot.

clt60
  • 62,119
  • 17
  • 107
  • 194
6

I would simply launch you script at midnight, and sleep for a random time between 0 and 86400 seconds. Since my bash's $RANDOM returns a number between 0 and 32767:

sleep $(( ($RANDOM % 1440)*60 + ($RANDOM % 60) ))
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
5

The best alternative to cron is probably at

Usually, at reads commands from standard input, but you can give a file of jobs with -f.

Time wise, you can specify many formats. Maybe in your case the most convenient would be

  • at -f jobs now + xxx minutes

where your scripts gives xxx as a random value from 1 to 1440 (1440 minutes in a day), and jobs contains the commands you want to be executed.

Déjà vu
  • 28,223
  • 6
  • 72
  • 100
1

You can use cron to launch bash script, which generates pseudorandom timestamp and gives it to unix program at

I see you are familiar with bash and cron enough, so at will be a piece of cake for you. Documentation as always "man at" or you can try wiki

http://en.wikipedia.org/wiki/At_(Unix)

bartimar
  • 3,374
  • 3
  • 30
  • 51
1

Nothing prevents you from running sed to patch your crontab as the last thing your program does and just changing the next start time. I wouldn't sleep well though.

user1666959
  • 1,805
  • 12
  • 11