I am having trouble regarding Cron jobs, I've basically got two PHP scripts that I want to keep running continuously on my server. Currently I am using an infinte loop to keep them going but they seem to stop at random times.

I'd ideally like to write a script that checks to see if the scripts are running and if they are not then to start them up.

I'm wondering how I might go about this?

  • How are you starting the script? You may need to use NOHUP or write an init script. Checkout 'fpm' for help on init scripts. – spuder Jun 6 '15 at 23:39

What you want is a daemon, not a cron job. A cron job is for executing something periodically (or at boot), not for keeping a process alive. I encourage you to read that article, then do something very simple like this:

while true
   /my/script.php >> /var/log/my_script.log 2>&1
|improve this answer|||||

To check for a runinng process you can list all the running processes (with ps) and then filter the one you're looking for with grep:

 ps aux | grep YOUR_PHP_COMMAND

If you want to start your command only when it's not running you can use the following script:

CMD="/bin/sleep 3" # replace it with your command
if ! ps x|grep -v grep|grep "$CMD"; then 

NOTE: You need to use 'grep -v grep' to exclude the grep process from the process list.

If you want to put it in a CRON JOB you can pack it in one line with ';'

CMD="/bin/sleep 3"  ;  if ! ps aux|grep -v grep|grep "$CMD"; then $CMD  ;  fi

Remember that CRON JOBs are good for scheduling things. If you only want to keep a program running, a better approach will be an infinite loop which start the program whenever it ends.

|improve this answer|||||
  • Currently I am using an infinite loop - something like this: nohup sh -c 'while true; do php get_tweets.php; done' >/dev/null & it works fine but when I check in the morning it seems to have stopped. – Javacadabra Sep 15 '14 at 9:18
  • I just read with my hosting service that if no http requests are recieved in 24 hours the system goes idle until the next http request, perhaps that explains why the scripts stop in the middle of the night – Javacadabra Sep 15 '14 at 9:32
  • 1
    Ok, make sense. Then you need a script to make an http request at least once every 24 hours :) – mxlian Sep 15 '14 at 9:51
  • -1 for a terrible solution to a common problem. – l0b0 Jun 7 '15 at 10:51
  • Just read the question again, and the last part of my answer... – mxlian Jun 7 '15 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.