[LINUX] One liner that randomly rewrites the startup time of cron

It is a small story.

Prerequisite knowledge

In bash, you can randomly get numbers from 0 to 32767 by using the environment variable $ RANDOM.

For example, to randomly display numbers from 0 to 3, combine the modulo operator symbols % as follows:

Randomly display numbers from 0 to 3


echo $((RANDOM % 4))

This is the number from 5 to 59.

Randomly display numbers from 5 to 59


echo $((5 + RANDOM % 55))

The explanation of this area was much easier to understand in [Randomly do it with a shell script], so please refer to that.

To rewrite the cron time field

The main subject. Suppose the following cron is defined on the last line:

00 2 * * * /home/mindwood/foo.sh > /dev/null 2>&1

It is set to start at 2:00 am, but I would like to set this to start from 0:05 am to 3:59 am and give it a range. On top of that, I want to avoid just every hour (1 am, 2 am ...).

Here is the one liner to rewrite.

H=$((RANDOM%4));M=$((5+RANDOM%55));sed -i -e '$s/^[0-9]\+ [0-9]\+/'$M' '$H'/' /var/spool/cron/crontabs/root

For example, it is updated as follows.

43 1 * * * /home/mindwood/foo.sh > /dev/null 2>&1

If you don't like this time, you can start over again.

Note that $ in sed represents the last line. For more information on sed, please refer to [How to write in this case with sed?].

Recommended Posts

One liner that randomly rewrites the startup time of cron
One liner that beautifully displays cron for all users
Grep so that grep does not appear at the time of grep
A function that measures the processing time of a method in python
Process the result of% time,% timeit
A note about the functions of the Linux standard library that handles time
This and that of the inclusion notation.
Python3 + pyperclip that rewrites the copied text
Stop the automatic startup of Apache Nginx
I made a tool to estimate the execution time of cron (+ PyPI debut)
The advantages and disadvantages of Django that people with one year of experience think
[Python] The movement of the decorator that can be understood this time ② The decorator that receives the argument
With LINEBot, I made an app that informs me of the "bus time"