3

I want a cronjob to run every one hour randomly. (i.e if the first job runs at 58 minutes,the second job should run at 47 minutes and the third one at 52 minutes and so on) But this should run randomly for everyone hour.

1 Answer 1

6

You can do this by defining a job which runs every hour on the hour, and sleeps for a random amount of time before running the command you're actually interested in. In your crontab:

SHELL=/bin/bash

0 * * * * sleep $((RANDOM*3600/32768)) && command

(You need to specify the shell, to ensure that $RANDOM is available. There are other ways of getting a random value for sleep if that's not appropriate.)

5
  • Thanks for the response. I will try it and let you know shortly.
    – User123
    May 31, 2016 at 7:28
  • Will it exactly runs 1hour once? I tried it seems to run once in an hour exactly, but not randomly like 54 minutes, 46 minutes, so on.
    – User123
    May 31, 2016 at 9:34
  • The cron job itself will run every hour on the hour exactly, but command within the cron job will run at some random minute in the hour. May 31, 2016 at 9:36
  • Could you explain this part, what is going on heree? $((RANDOM*3600/32768)) Aug 20, 2017 at 7:26
  • 4
    @user3128796, reading RANDOM gives a randomly-selected integer between 0 and 32767. Multiplying that by 3600 and dividing by 32768 results in an integer between 0 and 3599, and interpreting that in seconds gives a duration between nothing and just under one hour. Aug 20, 2017 at 7:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .