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
  • 56,954
  • 26
  • 136
  • 173
flaab
  • 465
  • 7
  • 18

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,237
  • 10
  • 54
  • 98
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
  • 429
  • 1
  • 6
  • 16
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
  • 40,497
  • 12
  • 76
  • 76
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.

0

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.
  • 2,945
  • 27
  • 27