如果在1秒钟之内没有新请求,PHP中是否有办法采取某种措施(例如,mysql插入)?

我要实现的目标是确定从IP摄像机发送的图像序列的开始和结束。相机在检测到运动时发送一系列图像,并在运动停止时停止发送图像。我知道相机每秒可以拍摄5张图像(每200ms)。当没有新图像的时间超过1秒时,我想将最后一张图像标记为序列的结尾,在mysql中插入一条记录,将img放置在适当的文件夹中(其中来自同一序列的所有其他img已被写入)并指示app在该文件夹中制作图像的MJPEG剪辑。

现在,我可以使用Alternative PHP cash确定序列中的第一个图像,以节省上一个请求的引用时间,但是问题是因为下一个图像序列可以在数小时后发生,并且如果没有请求,我无法指示PHP关闭序列在一段时间内,仅当新序列的第一个请求到达时。

我真的需要帮助。我的PHP几乎就像我的英语一样糟糕... :)

我的问题的伪代码:

<?php
  if(isset($headers["Content-Disposition"]))
    {
        $frame_time = microtime(true);
      if(preg_match('/.*filename=[\'\"]([^\'\"]+)/', $headers["Content-Disposition"], $matches))
      { $filename = $matches[1]; }
      else if(preg_match("/.*filename=([^ ]+)/", $headers["Content-Disposition"], $matches))
      { $filename = $matches[1]; }
    }
  preg_match("/(anpr[1-9])/", $filename, $anprs);
  $anpr = $anprs[1];
  $apc_key = $anpr."_last_time"; //there are several cameras so I have to distinguish those
  $last  = apc_fetch($apc_key);
  if (($frame_time - $last)>1)
         {
            $stream = "START"; //New sequence starts
         } else {
            $stream = "-->"; //Streaming
         };
   $file = fopen('php://input', 'r');
   $temp = fopen("test/".$filename, 'w');
   $imageSize = stream_copy_to_stream($file, $temp); //save image file on the file system
   fclose($temp);
   fclose($file);

   apc_store($apc_key, $frame_time); //replace cashed time with this frame time in APC

  // here goes mysql stuff...

  /* Now... if there is no new requests for 1 second $stream = "END";
  calling app with exec() or similar to grab all images in the particular folder and make
 MJPEG... if new request arrives cancel timer or whatever and execute script again. */

?>

最佳答案

您能否在退出前1.5秒使每个请求都处于休眠状态,并作为最后一步检查序列时间戳是否已更新?如果是,请退出并不执行任何操作。如果否,则将序列保存到mysql。 (这将需要互斥锁,因为每个http请求都将进行检查并尝试保存序列,但必须只允许一个。)

这种方法会将子文件/脚本合并到php代码中(单个代码库,更易于维护),但它可能会增加内存使用量(每个请求将在内存中保留1.5秒,这对于繁忙的服务器来说是很长的时间) 。

另一种方法是将子文件/脚本转换为本地主机http服务器上的回送请求,其内存占用空间可能要小得多。每个帧都会触发一个确定序列的请求(同样,使用互斥锁)。

或者,也许创建一个单独的服务调用来检查并保存所有序列,并执行cron作业每隔几秒钟ping它一次。或让每个帧ping它,如果第二个请求可以检测到该服务已在运行,则可以退出。 (APC缓存中的共享状态)

编辑:我想我只是建议上面所说的字节化。

关于php - 如果一段时间没有新请求,是否可以执行PHP脚本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27096547/

10-12 07:39
查看更多