How do I make cron run something every "N"th minute, where n % 5 == 1?

Viewed 29701

I know that I can have something run every five minutes in cron with a line like:

 */5 * * * * /my/script

What if I don't want it running at 12:00, 12:05, 12:10, but rather at 12:01, 12:06, 12:11, etc? I guess I can do this:

 1,6,11,16,21,26,31,36,41,46,51,56 * * * * /my/script

...but that's ugly. Is there a more elegant way to do it?

5 Answers
1-56/5 * * * * /my/script

This should work on vixiecron, I'm not sure about other implementations.

Use your first schedule:

*/5 * * * * /my/script

And add this to the start of your script:

sleep 60

(Yes, this is a joke)

This is quite an old topic, however as so much time has passed there are a few other options now. One of which is not to use cron at all, and use systemd timers. Using these gives you a higher granularity than seconds along with lots of other options

More information is available here https://wiki.archlinux.org/index.php/Systemd/Timers

eg to run a adhoc command

# systemd-run --on-calendar="*:1/5" /bin/touch /tmp/foo2
Running timer as unit run-r31335c4878f24f90b02c8ebed319ca60.timer.
Will run service as unit run-r31335c4878f24f90b02c8ebed319ca60.service.

# systemctl status run-r31335c4878f24f90b02c8ebed319ca60.timer
● run-r31335c4878f24f90b02c8ebed319ca60.timer - /bin/touch /tmp/foo2
   Loaded: loaded
Transient: yes
  Drop-In: /run/systemd/system/run-r31335c4878f24f90b02c8ebed319ca60.timer.d
           └─50-Description.conf, 50-OnCalendar.conf, 50-RemainAfterElapse.conf
   Active: active (waiting) since Wed 2017-10-25 09:05:13 UTC; 40s ago

# ls -l  /tmp/foo*
-rw-r--r-- 1 root root 0 Oct 25 09:06 /tmp/foo2

# sleep 300; ls -l  /tmp/foo*
-rw-r--r-- 1 root root 0 Oct 25 09:11 /tmp/foo2

# date; ls -l /tmp/foo2
Wed Oct 25 09:21:42 UTC 2017
-rw-r--r-- 1 root root 0 Oct 25 09:21 /tmp/foo2

edit: these type of timers wont persist over reboot, if you want them to make sure you generate a proper service file, with the relevant oncalendar line

sean.bright's joke got me thinking... why not use...

* * * * * /my/script

...and within the script do this...

#!/bin/bash
export WHEN=`date '+%M'`
echo $WHEN
export DOIT=`echo "$WHEN % 5" | bc` 
echo $DOIT
if [ $DOIT != 0 ] ; then
    echo "ha ha ha"
fi
echo "done"

...a kludge... maybe, but as ugly as the crontab... I don't know.

Related