2

I'm mucking about with daemons, and wondered how feasible (in terms of memory and cpu usage, and reliability) it is to do this using PHP:

<?php
// Ignore user aborts and allow the script
// to run forever
ignore_user_abort(true);
set_time_limit(0);

$fp = fopen('loop.log', 'w');
fwrite($fp, date('Y-m-d H:i:s') . ' Started' . PHP_EOL);
while(1) {
    fwrite($fp, date('Y-m-d H:i:s') . ' Looped' . PHP_EOL);
    if (file_exists('loop.stop')) {
        break;
    }
    // Sleep for 100 seconds
    sleep(100);
}
fwrite($fp, date('Y-m-d H:i:s') . ' Stopped' . PHP_EOL);
fclose($fp);

This simple example (adapted from the PHP manual for ignore_user_abort) is just the container script. The actual functionality will be placed inside the while loop.

I've got this script running on my laptop for 7 hours now, and it looks fine, but it doesn't do much. Has anyone else tried this?

hakre
  • 193,403
  • 52
  • 435
  • 836
Jrgns
  • 24,699
  • 18
  • 71
  • 77

3 Answers3

3

I would tend to put the loop into a BASH script, so that any PHP resources are regularly cleaned up.

#!/bin/bash
clear
date

php -f doChecksAndAct.php
sleep 100
# rerun myself
exec $0

If you were doing any particularly heavy-to-setup tasks in the PHP script, you could also put a small(ish) loop in there (say 50-100 iterations, if they were not pausing multiple seconds between them) to reduce the total overhead time between runs.

Addition: I've blogged on a Bash/PHP (or other language) pairing so that you can very easily loop in the PHP script, then exit to restart immediately, or pause for a while - Doing the work elsewhere -- Sidebar running the worker.

Alister Bulman
  • 34,482
  • 9
  • 71
  • 110
1

I recommend against it.

There is a bug open 4 years ago which says Memory allocated for objects created in object methods is not released.

The devs consider this a Feature request but it's very hard to work around it when using long-running processes. I tried to but was extremely relieved when I was able to retire the application.

Robert Munteanu
  • 67,031
  • 36
  • 206
  • 278
0

sonic server daemon might be worth checking out aswell

http://dev.pedemont.com/sonic

anon
  • 1