Running a cron job every 30 seconds

By: Shane Harter|Last Updated: Feb 07, 2024

In a standard linux cron expression, you have 5 fields: minute, hour, day-of-month, month, and day-of-week. With these fields you can create endless combinations of cron schedules, but none will run more frequently than once a minute. This guide will show you a simple way to overcome this limitation and run your cron jobs every 30 seconds.

How to run a cron job every 30 seconds

To run a cron job every 30 seconds, schedule an every minute crontab entry, and use a bash script to run your job twice, with a 30-second sleep in between. Here's an example of that shell script:

for (( i=1; i<=2; i++ )); do
    # Invoke your command here, the same as you would from your crontab
    # The & at the end will run the job in a background shell, so the 30 second sleep will start immediately 
    python /home/crons/ &
    sleep 30

In this scenario, we will save this script as /home/crons/, but wherever you save it, don't forget to make it executable by running chmod +x /home/crons/ This is what your crontab entry should look like:

* * * * * /home/crons/

One common problem with any frequently-running cron job is that a small problem can cause job processes to accumulate until the host is saturated. Only use this technique if you are certain that your job is doing something that is very fast. You should also consider using flock to actively ensure multiple copies of your job can't be run at the same time. You could use flock in the bash script above, on the same line where we invoke the command, or you can add flock to the every-minute crontab entry that invokes the bash script:

* * * * * flock -n /home/crons/send-updates-wrapper.lock /home/crons/

Better support beyond Linux cron

As useful as Linux cron is, it was not created for this level of schedule granularity. An alternative to this method, is to use one of the popular runtime-based schedulers that are probably available for your platform. Here are a few examples:

Spring CronJava (Quartz)Docs
Node CronNode.jsNPM
Go CronGolangReadme
SystemD TimerLinuxExample OnCalendar=*-*-* *:*:00,30

Monitoring your frequent cron jobs

If you are using the shell script to run your job twice a minute, you will not be able to monitor each execution by simply using cronitor discover to monitor your crontab. Instead, you will want to add cronitor exec calls yourself to the wrapper script.

For example, change this line:

python /home/crons/ &

To this:

cronitor exec send-updates "python /home/crons/" &

When this runs, a monitor called send-updates will be created automatically on your dashboard, and you can configure it from there, adding a name and schedule, e.g. every 30 seconds.

Want alerts if your cron jobs stop working?

Monitor your cron jobs with Cronitor to easily collect output, capture errors and alert you when something goes wrong.