1

I'm writing a PHP script (OK, it's a daemon worker) that I'd like to run in the background, and it follows the following pseudo-code:

do {
    // stuff
    sleep(60*30); // 30 minutes
} while(1);

Now, how can I set this baby up to run automatically in the event that the server gets restarted. I don't need to worry about state, since everything is stored in the MySQL DB - and it should just be able to pick up right where it left off.

I'm using an Ubuntu 12.04 x64 server, on AWS (if that matters).

Thanks!

FloatingRock
  • 6,741
  • 6
  • 42
  • 75
  • 1
    dropping the sleep() and making it run every 30 mins as a cronjob may be a better option – guido Aug 31 '13 at 06:06
  • @guido what if it doesn't manage to finish in 30 minutes? I'll have 2 processes running at the same time. – FloatingRock Aug 31 '13 at 06:06
  • 1
    @FloatingRock usually I drop a blank zero byte file at start of my cron, this works as LOCK, if the lock file is available to halt execution, otherwise I proceed with it and at end of script I delete that lock file. then set it through crone. It is good idea to use cron as it use less memory than your script executing with 30 minute sleep. – Sumit Gupta Aug 31 '13 at 06:09
  • 1
    @FloatingRock In that case, use a lock file. If the lock file exists, don't do anything and exit right away. Otherwise, create the lock file, process one `stuff` and then delete the lock file. You should also check the age of the lock file, if it is much older than you expect `stuff` to take, then ignore the lock file as it is "stale". – leftclickben Aug 31 '13 at 06:09
  • @SumitGupta ok, so I take it there's no way this can be set up to run on server start? (besides using cron) – FloatingRock Aug 31 '13 at 06:12
  • you could have a bash script in init.d that calls `curl http://127.0.0.1/site/myscript.php` – ddavison Aug 31 '13 at 06:23
  • 1
    there is a way, i.e. the bash script as previous comment, but instead of http://, I suggest using php cli, because http has time limit, and since you want to run it whole server life, php cli is best to have. – Sumit Gupta Aug 31 '13 at 06:27

1 Answers1

0

As a solution to your specific problem use bash script to execute PHP cli Pusedo code will be

\usr\sbin\php -q \home\user\myphpscript.php

this will execute the PHP script without any time constrain, however since you use PHP CLI you might not get some environment variables, which are web specific, but for such background process you hardly need them anyways.

Sumit Gupta
  • 2,152
  • 4
  • 29
  • 46