skip to content

Job Scheduling Every Second

/ 2 min read

Cron Sidekick for an infinite loop script ∞ If you need speed?

🎛️ Script that Runs Every Second and its Cron Sidekick

Okay, so you’re a speedster who can’t wait a whole minute for cron to run your script 😅🤣 You need it to execute every second! Unfortunately, cron wasn’t built to support second-level tasks, but I’ve got a workaround for your speedsters out there.

🎳 The Script That Loops

First, create a script that runs an infinite loop with a sleep command for one second. Here’s a simple example in bash:

#!/bin/bash
while true; do
    echo "This is running every second" >> /path/to/logfile.log
    sleep 1
done

Make your script executable:

chmod +x your-script.sh

🏃‍♂️ Running the Script

You can run this script in the background like so:

./your-script.sh &

Or you could use nohup to keep the script running even after logging out:

nohup ./your-script.sh &

🛠️ Cron’s Sidekick Role

While cron can’t run a script every second, it can make sure your “every-second” script is running as expected. You can create another script that checks if the first script is running and starts it if it’s not.

Here’s an example:

#!/bin/bash
if pgrep -f "your-script.sh" > /dev/null
then
    echo "Script is running" >> /path/to/status.log
else
    nohup /path/to/your-script.sh &
    echo "Script was not running. Starting it now." >> /path/to/status.log
fi

📆 Scheduling with Cron

Now you can schedule this checking script with cron to run every minute:

* * * * * /path/to/your-checking-script.sh

Tadaa! While cron may not be able to run tasks every second, it sure can act as a trusty sidekick to make sure your speedster script is running as it should. 🤓