使用ignore_user abort和set_time_limit(0)用PHP编写的守护程序的可行性如何 [英] How feasible is a daemon written in PHP, using ignore_user abort and set_time_limit(0)

查看:100
本文介绍了使用ignore_user abort和set_time_limit(0)用PHP编写的守护程序的可行性如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑使用守护程序,并想知道使用PHP做到这一点的可行性(就内存和cpu的使用以及可靠性而言):

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);

这个简单的示例(改编自PHP手册,用于 ignore_user_abort )只是容器脚本.实际功能将放置在while循环内.

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.

我已经在笔记本电脑上运行了7个小时,该脚本看起来还不错,但是并不能做很多事情.还有其他人尝试过吗?

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?

推荐答案

我倾向于将循环放入BASH脚本中,以便定期清理所有PHP资源.

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

如果您要在PHP脚本中执行任何特别繁重的设置任务,则还可以在其中放置一个小(ish)循环(例如50-100次迭代,如果它们之间没有暂停几秒钟)减少运行之间的总开销时间.

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.

添加:我已经在Bash/PHP(或其他语言)配对上写博客,以便您可以非常轻松地循环播放PHP脚本,然后退出以立即重新启动,或暂停一会儿-在其他地方进行工作-边栏运行工作者.

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.

这篇关于使用ignore_user abort和set_time_limit(0)用PHP编写的守护程序的可行性如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆