Arnaud Dubois
Arnaud Dubois

Reputation: 124

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

Upvotes: -2

Views: 210

Answers (2)

Arnaud Dubois
Arnaud Dubois

Reputation: 124

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

Upvotes: 1

adervisevic
adervisevic

Reputation: 21

Here you have a simple bash script that will generate two separate cron jobs for the first run and the second one.

Please change the cmd variable to your command of choice or script. (Note: If setting a script, make sure it is executable!)

#!/bin/bash

# Define the command you want to run
cmd="your_command_here"

# Generate random hour and minute for the first run
hour1=$((RANDOM % 24))
minute1=$((RANDOM % 60))

# Generate random hour and minute for the second run
hour2=$((RANDOM % 24))
minute2=$((RANDOM % 60))

# Create cronjobs for the two random times
(crontab -l 2>/dev/null; echo "$minute1 $hour1 * * * $cmd") | crontab -
(crontab -l 2>/dev/null; echo "$minute2 $hour2 * * * $cmd") | crontab -

Upvotes: 2

Related Questions