2

I would like to run a cron job every 30 seconds, but cron does not allow scheduling jobs more frequently than once a minute.

Which is the best way to run a cron job every 30 seconds?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
flaab
  • 543
  • 9
  • 19

5 Answers5

3

Here's a way to do this while avoiding the sliding window issue. Create two scripts, your main one (main.sh here) and a sleep script (sleep30.sh):

main.sh:

#!/bin/bash
date >>/tmp/main.out

sleep30.sh:

#!/bin/bash
sleep 30
. $1

crontab:

* * * * * /pathtoscripts/sleep30.sh /pathtoscripts/main.sh
* * * * * /pathtoscripts/main.sh

It's inelegant, but should work.

Don Branson
  • 13,631
  • 10
  • 59
  • 101
2

In case task execution time is short and can be neglected, you can do it this way:

* * * * * /path/cmd; sleep 30; /path/cmd
Dima L.
  • 3,443
  • 33
  • 30
1

The shortest time interval you can use with cron is 1 minute. You could put a sleep in a bash script, but that would probably be the best you can do

Dace
  • 489
  • 1
  • 7
  • 17
0

The short answer is that you can't schedule cron jobs under a minute. You can use sleep 30 but that introduces sliding window problems (the task is now intervaled at 30 seconds + run time of the task). You can put the task inside a while true loop and have it check each iteration if at least 30 seconds have passed, and if so - run the task again, and if not sleep 1

sampson-chen
  • 45,805
  • 12
  • 84
  • 81
0

You can upgrade to the latest beta of FreeBSD which has a special new cron modifier: @every_second. Wrap your cronjob in lockf, sleep for 30 seconds, run the job, and terminate. This way you can run it twice a minute.