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:

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

Make your script executable:

chmod +x

🏃‍♂️ Running the Script

You can run this script in the background like so:

./ &

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

nohup ./ &

🛠️ 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:

if pgrep -f "" > /dev/null
    echo "Script is running" >> /path/to/status.log
    nohup /path/to/ &
    echo "Script was not running. Starting it now." >> /path/to/status.log

📆 Scheduling with Cron

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

* * * * * /path/to/

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. 🤓