cronredhatrpmrpmbuildrocky-os

Need a cron job that runs twice a day at random time


I need to implement a cron job that runs twice a day at 12hhjous of interval at random times.

The objective is to deploy an rpm package containing the cron task but the cron task won't execute at the same time on every deployed machines

I read a lot of similar problems on StackOverflow but none answered my question and i cannot find an appropriate solution.

I do not want to use the sleep method.

Just two entries in a cron


Solution

  • The solution I found has been to implement this functionnality in my specfile in the %post section

    sed -i "s|RANDOM_MINUTE|$(( RANDOM % 60 ))|g" /etc/cron.d/myCommand.new
    cronHour=$(( RANDOM % 12 ))
    sed -i "s|RANDOM_HOUR_AM|$cronHour|g" /etc/cron.d/myCommand.new
    sed -i "s|RANDOM_HOUR_PM|$(( $cronHour + 12 ))|g" /etc/cron.d/myCommand.new
    tmpvar=`cat myCommand.new`
    crontab -l | awk -v finalCronLine="$tmpvar" '{print} END {print finalCronLine}' | crontab
    

    Content of the myCommand.new file

    RANDOM_MINUTE RANDOM_HOUR_AM,RANDOM_HOUR_PM * * * myScript.sh
    
    

    This way myCommand is played twice a day at 12 hours of interval at random times.

    Random minutes and hours are calculated during the installation process, so, on the machine on which agent is deployed which means that they're not the same on every system and avoids high server workload