使用CLI每秒运行一个PHP脚本 [英] Run a PHP script every second using CLI
问题描述
我有一个专用的服务器运行Cent OS并行PLESK面板。我需要每秒运行一个PHP脚本来更新我的数据库。
我可以使用URL http://找到我的脚本www.mysite.com/phpfile.php?key=123
。
文件每秒可以在本地执行吗?喜欢 phpfile.php
?
更新:
我添加了这个问题已经有几个月了。我最后使用以下代码:
#!/ user / bin / php
<?php
$ start = microtime(true);
set_time_limit(60);
for($ i = 0; $ i <59; ++ $ i){
doMyThings();
time_sleep_until($ start + $ i + 1);
}
?>
我的cronjob设置为每分钟。我已经在测试环境中运行了一段时间,它已经工作得很好。它真的超级快,我看不到CPU和内存使用的增加。
你实际上可以在PHP。写一个程序将运行59秒,每秒进行检查,然后终止。
一种方法是:
$ b $ set_time_limit(60);
for($ i = 0; $ i <59; ++ $ i){
doMyThings();
sleep(1);
}
你可能需要注意的唯一的事情是运行时间的 doMyThings()
函数。即使这只是一秒钟的一小部分,然后超过60次迭代,这可能加起来导致一些问题。如果你运行PHP> = 5.1(或Windows上的> = 5.3),那么你可以使用 time_sleep_until()
$ start = microtime(true);
set_time_limit(60);
for($ i = 0; $ i <59; ++ $ i){
doMyThings();
time_sleep_until($ start + $ i + 1);
}
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.
I can find my script using the URL http://www.mysite.com/phpfile.php?key=123
.
Can the file be executed locally every second? Like phpfile.php
?
Update:
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);
}
?>
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.
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.
One approach is this:
set_time_limit(60);
for ($i = 0; $i < 59; ++$i) {
doMyThings();
sleep(1);
}
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屋!