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

49 Views Asked by At

I need to implement a cron job that runs twice a day at random time.

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

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

I do not want to use the sleep method because this would involve a sleep random(43200) and I think it's too much

1

There are 1 best solutions below

0
On

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 -