2

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.

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.)

  • Thanks for the response. I will try it and let you know shortly. – User123 May 31 '16 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 '16 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. – Stephen Kitt May 31 '16 at 9:36
  • Could you explain this part, what is going on heree? $((RANDOM*3600/32768)) – user3128796 Aug 20 '17 at 7:26
  • 3
    @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. – Stephen Kitt Aug 20 '17 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.