Linux – How to setup a cron job every random weekday

bashcentoscronlinuxUbuntu

As the question is fairly self-explanatory, I would like to know how to set a cronjob to execute any random weekday without using any external script.

EDIT: In case people have not understood this question, We have 5 weekdays, viz., Monday, Tuesday, Wednesday, Thursday, Friday. I have a server running 24/7. I want to set a cron that will run on any 1 weekday per week.

Note: I highly doubt this is a duplicate question, as this question is not pertaining to daily/weekly/monthly cronjobs.

Best Answer

Would something like this work for you? It selects a random day from a bash array days (note the SHELL prefix) and then writes a cronjob (random_runner) under /etc/cron.d to run the script /home/foobar/myscript.

You could place this in /etc/cron.d/random_generator and generate a new "runner" every day.

SHELL=/bin/bash
27 8 * * * root  days=(Mon Tue Wed Thu Fri Sat Sun); rd="$(( RANDOM \% 7 ))"; day="${days[$rd]}"; echo "45 15 * * $day root /home/foobar/myscript" > /etc/cron.d/random_runner