使用 CLI 每秒运行一个 PHP 脚本 [英] Run a PHP script every second using CLI

查看:28
本文介绍了使用 CLI 每秒运行一个 PHP 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一台运行 Cent OS 的专用服务器,带有 Parallel PLESK 面板.我需要每秒运行一个 PHP 脚本来更新我的数据库.这些在时间上没有替代方法,它需要每秒更新一次.

I have a dedicated server running Cent OS with a Parallel PLESK panel. I need to run a PHP script every second to update my database. These is no alternative way time-wise, it needs to be updated every second.

我可以使用 URL http://www.somesite.com/phpfile.php?key=123 找到我的脚本.

I can find my script using the URL http://www.somesite.com/phpfile.php?key=123.

文件可以本地每秒执行一次吗?像phpfile.php?

Can the file be executed locally every second? Like phpfile.php?

更新:

我添加这个问题已经有几个月了.我最终使用了以下代码:

It has been a few months since I added this question. I ended up using the following code:

#!/user/bin/php
<?php
$start = microtime(true);
set_time_limit(60);
for ($i = 0; $i < 59; ++$i) {
    doMyThings();
    time_sleep_until($start + $i + 1);
}
?>

我的定时任务设置为每分钟.我已经在测试环境中运行了一段时间,并且效果很好.真的超级快,我看不到 CPU 和内存使用量的增加.

My cronjob is set to every minute. I have been running this for some time now in a test environment, and it has worked great. It is really super fast, and I see no increase in CPU nor Memory usage.

推荐答案

您实际上可以在 PHP 中完成.编写一个程序,该程序将运行 59 秒,每秒执行一次检查,然后终止.将此与每分钟运行 那个 进程的 cron 作业结合起来,嘿嘿.

You could actually do it in PHP. Write one program which will run for 59 seconds, doing your checks every second, and then terminates. Combine this with a cron job which runs that process every minute and hey presto.

一种方法是这样的:

set_time_limit(60);
for ($i = 0; $i < 59; ++$i) {
    doMyThings();
    sleep(1);
}

您可能唯一需要注意的是 doMyThings() 函数的运行时间.即使那是几分之一秒,然后超过 60 次迭代,加起来也可能会导致一些问题.如果您运行 PHP >= 5.1(或在 Windows 上 >= 5.3),那么您可以使用 time_sleep_until()

The only thing you'd probably have to watch out for is the running time of your doMyThings() functions. Even if that's a fraction of a second, then over 60 iterations, that could add up to cause some problems. If you're running PHP >= 5.1 (or >= 5.3 on Windows) then you could use time_sleep_until()

$start = microtime(true);
set_time_limit(60);
for ($i = 0; $i < 59; ++$i) {
    doMyThings();
    time_sleep_until($start + $i + 1);
}

这篇关于使用 CLI 每秒运行一个 PHP 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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