【问题标题】:Code start and end in specific time代码在特定时间开始和结束
【发布时间】:2017-04-02 07:39:41
【问题描述】:

大家好,我有一个在特定时间开始和结束的代码,我的代码工作正常,但我想在循环的数据中使用这个代码 例如,我将在循环中输入名称,并且我希望每个名称在特定时间开始和结束:

这是我的代码:

<?php
date_default_timezone_set('America/New_York');
$time = date('Y:m:d H:i:s');
$timestart = date('Y:m:d H:i:s'); //time start
$timeend = '2016:11:17 10:56:00'; //time end

if($time >= $timeend){
echo "time end";
}else{
    echo 'untel end time';
    }


$now = new DateTime();
$future_date = new DateTime($timeend);
$interval = $future_date->diff($now);
?>

我想知道如何将它与循环数据一起使用?

谢谢。

【问题讨论】:

  • 你需要 cron 在设定的时间运行脚本
  • 不需要 cron
  • 那么您是否在连续循环中运行脚本,一遍又一遍地检查时间?
  • 是的,我的 sql 中有数据,我通过循环在 php 中获取它,我希望每个数据都在我选择的时间结束
  • 这是一个可怕的想法。最终,您将耗尽资源或脚本将失败。我强烈建议使用 cron,以便在特定时间触发文件。

标签: php date dst


【解决方案1】:

您可以使用 EV 或 Event 扩展或循环实现。我更喜欢 EV 扩展来完成这项任务

并创建计时器例如:

// Required create variable!
$w = new EvTimer($needWorkedSeconds, $repeatAfterSecond, function ($w) {
    echo "iteration = ", Ev::iteration(), PHP_EOL;
});

// Loop until Ev::stop() is called or all of watchers stop
Ev::run();

More read here!

或使用事件(但我更喜欢事件与套接字一起使用):

$base = new \EventBase();
$e = \Event::timer($base, function($n) use (&$e) {
    echo "$n seconds elapsed\n";
    if($isTimeEndNow)
    {
         $e->delTimer();
    }
}, $repeatAfterSecond);
$e->addTimer($repeatAfterSecond);
$base->loop();

More read here!

或者你可以试试while,例如:

while(true)
{
    if($isTimeEndNow)
    {
         break;
    }
    sleep($repeatAfterSecond);
}

在示例中我使用未声明的变量:

$repeatAfterSecond - seconds to next iteration or next call
$isTimeEndNow - this is: time() > $endTimestamp
$needWorkedSeconds - this is seconds: time_start - time_end

注意!!!小心!我认为你犯了错误,如果你想使用 MySQL 并且你需要在具体时间使用脚本。检查你的算法!!!

【讨论】:

    猜你喜欢
    • 2022-12-08
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多