How feasible is a daemon written in PHP, using ignore_user abort and set_time_limit(0)

核能气质少年 提交于 2019-12-30 05:21:06

问题


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?


回答1:


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.




回答2:


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.




回答3:


sonic server daemon might be worth checking out aswell

http://dev.pedemont.com/sonic



来源:https://stackoverflow.com/questions/1006891/how-feasible-is-a-daemon-written-in-php-using-ignore-user-abort-and-set-time-li

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!