Beamtic's logo

Share via:

Run a Cron Job Every Minute or Second

This tutorial describes how to schedule a cron job to run every minute using crontab -e; if finer control is needed, it is suggested that we use a loop with a sleep of a few seconds.

69 views

Edited: 2020-08-29 12:30

Sometimes we might need to run a cron job every minute; when using crontab -e to schedule our cron jobs, this is the lowest interval possible. If, for example, we need to run something every second, we will instead need to use a loop inside a script.

To run a cron job every minute we may use the below syntax:

* * * * * /path/to/script.sh

This would run the script.sh file every minute.

If finer control is needed, we should instead create a script with a loop inside that calls another script as needed. If we needed to call a script every second, we could just add a sleep of 1000 milliseconds inside the loop of the script.

We might also want to add a check to see if the script is already running, that way, when the cron job is executed, it will result in multiple instances of the same script. Alternatively, we can simply stop the loop after 59 seconds or so and have cron activate the script again.

An example of how to do this:

#!/bin/bash

i=1
while (( $i <= 59 ))
do
        # Here we may do something every second. I.e. Write to a file?
        echo $i >> /home/k/Documents/test.txt
        i=$(( i+1 ))
        sleep 1s
done

Comments