Search code examples
timercentosbackground-processperiodic-task

Run command every 30 seconds in background on CentOS


The title says it all:

How can I run some command every 30 seconds in the background on CentOS indefinitely? That is: I want to be able to do other stuff while some other script is called periodically.


Solution

  • By default, cron cannot schedule jobs to be run in seconds. The most you can do is to run it every minute.

    1) run it by a single cron

    To run it by cron, every 30 seconds you can create one single cron entry like this:

    * * * * * /bin/bash -l -c "/path/to/script.sh; sleep 30 ; /path/to/script.sh"
    

    2) run it using watch

    Run the script using watch ((you can start it a screen or tmux) or even in background)

    watch --interval 30 /path/to/script.sh 
    

    3) use a while loop like this:

    #!/bin/env bash
    while [ true ]; do
     sleep 30
     /path/to/script.sh
    done
    

    Keep in mind that this option is not fail proof since it all depends on what exactly your cron does and how long it takes for the job ran by cron to complete. With the above example (3), if the cron takes 25 seconds to run, then your script will get delayed and so on. Same applies to option (1) as well

    4) using an alternative cron to the default linux cron (use fcron)

    5) Similar questions were already asked on SO so you might want to take a look at this: How to run Cronjobs more often than once per minute?