php while循环,其中基于一天中的时间运行功能

时间:2018-08-09 19:06:51

标签: php

我在一个单独的php文件中创建了两个函数,并希望它们一遍又一遍地运行。

function A完成后,我希望它比较当前时间(相对于上次运行function B的时间),如果经过了24小时以上(或我设置的任何值),运行function B,在下次应触发运行时重置下一次,然后继续运行function A。它们需要单独运行而不是并行运行,因为function A中更改的值会影响function B,因此需要分开。理想的情况是我有一个config.php文件,可以在其中设置时间延迟(以小时为单位),但是我可以稍后再解决!

我很困惑如何组织这个while(true){}循环……有什么想法吗?

2 个答案:

答案 0 :(得分:1)

无论您是否最终以这种方式进行操作(因为我认为有关cron的评论都具有一定的意义,并且连续运行这样的PHP脚本可能还会遇到其他一些问题),这是根据定义的延迟执行备用功能。

// define the delay and initialize the timestamp
$delay = 86400;        // 24 hours, for example
$last_time = time();

while (true) {
    functionA();
    // the next time functionB should execute is the timestamp for the last run + the delay
    if (time() > $last_time + $delay) {
        functionB();
        $last_time = time();   // reset the timestamp
    }
}

答案 1 :(得分:0)

这种性质的东西是否与您要寻找的东西相似?

while ($time > 13 && $time < 21)

每个函数中也可能包含标志。如果触发了布尔标志且其值为1,则继续吗?