• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP usleep函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中usleep函数的典型用法代码示例。如果您正苦于以下问题:PHP usleep函数的具体用法?PHP usleep怎么用?PHP usleep使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了usleep函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: save

 public function save($str)
 {
     if (!$this->logFilename) {
         return false;
     }
     $hash = md5($str);
     // if we've already logged this during this session, then don't do it again
     if (in_array($hash, $this->itemsLogged)) {
         return true;
     }
     $ts = date("Y-m-d H:i:s");
     $str = $this->cleanStr($str);
     if ($fp = fopen($this->logFilename, "a")) {
         $trys = 0;
         $stop = false;
         while (!$stop) {
             if (flock($fp, LOCK_EX)) {
                 fwrite($fp, "{$ts}{$this->delimeter}{$str}\n");
                 flock($fp, LOCK_UN);
                 $this->itemsLogged[] = $hash;
                 $stop = true;
             } else {
                 usleep(2000);
                 if ($trys++ > 20) {
                     $stop = true;
                 }
             }
         }
         fclose($fp);
         return true;
     } else {
         return false;
     }
 }
开发者ID:gusdecool,项目名称:bunga-wire,代码行数:34,代码来源:FileLog.php


示例2: lock

 /**
  * Lock the resource
  *
  * @param  bool        $blocking wait until the lock is released
  * @return bool        Returns true if the lock was acquired, false otherwise
  * @throws IOException If the lock file could not be created or opened
  */
 public function lock($blocking = false)
 {
     if ($this->handle) {
         return true;
     }
     // Silence both userland and native PHP error handlers
     $errorLevel = error_reporting(0);
     set_error_handler('var_dump', 0);
     if (!($this->handle = fopen($this->file, 'r'))) {
         if ($this->handle = fopen($this->file, 'x')) {
             chmod($this->file, 0444);
         } elseif (!($this->handle = fopen($this->file, 'r'))) {
             usleep(100);
             // Give some time for chmod() to complete
             $this->handle = fopen($this->file, 'r');
         }
     }
     restore_error_handler();
     error_reporting($errorLevel);
     if (!$this->handle) {
         $error = error_get_last();
         throw new IOException($error['message'], 0, null, $this->file);
     }
     // On Windows, even if PHP doc says the contrary, LOCK_NB works, see
     // https://bugs.php.net/54129
     if (!flock($this->handle, LOCK_EX | ($blocking ? 0 : LOCK_NB))) {
         fclose($this->handle);
         $this->handle = null;
         return false;
     }
     return true;
 }
开发者ID:neteasy-work,项目名称:hkgbf_crm,代码行数:39,代码来源:LockHandler.php


示例3: gpio

function gpio($ettings, $target)
{
    $tatus = readGPIO($target);
    $gpio = $target['gpioNumber'];
    //read in cmd flag if set
    $cmd = isset($_GET["cmd"]) ? $_GET["cmd"] : null;
    //test if value is a number
    if (is_numeric($target['gpioNumber'])) {
        //set the gpio's mode to output
        setMode($target, "out");
        //toggle the gpio to high/low
        $tatus = $tatus == "0" ? 1 : 0;
        //check for commanded status flag and act upon it.
        if (isset($cmd)) {
            $tatus = $cmd == "off" ? 0 : 1;
        }
        writeGPIO($target, $tatus);
        //reading pin's status
        $status = readGPIO($target);
        echo $status;
        writeTimeStamp();
        //only wait to change state if default state is not current state
        if ($target['state'] != readGPIO($target)) {
            if (isset($target['timer']) && $target['timer'] > 0) {
                usleep($target['timer'] * 1000000);
                writeDefaultToGPIO($target);
            }
        }
    } else {
        echo "fail";
    }
    writeTimeStamp();
}
开发者ID:adamoutler,项目名称:RaspberryPiGPIOControl,代码行数:33,代码来源:GPIO.php


示例4: execute

 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $projectUuid = $input->getArgument('project-uuid');
     $api = $this->getApplication()->getApi();
     $analysis = $api->analyze($projectUuid, $input->getOption('reference'));
     $chars = array('-', '\\', '|', '/');
     $position = 0;
     while (true) {
         // we don't check the status too often
         if (0 == $position % 2) {
             $analysis = $api->getAnalysisStatus($projectUuid, $analysis->getNumber());
         }
         if ('txt' === $input->getOption('format')) {
             $output->write(sprintf("%s %-80s\r", $chars[$position % 4], $analysis->getStatusMessage()));
         }
         if ($analysis->isFinished()) {
             break;
         }
         usleep(200000);
         ++$position;
     }
     $analysis = $api->getAnalysis($projectUuid, $analysis->getNumber());
     if ($analysis->isFailed()) {
         $output->writeln(sprintf('There was an error: "%s"', $analysis->getFailureMessage()));
         return 1;
     }
     $helper = new DescriptorHelper($api->getSerializer());
     $helper->describe($output, $analysis, $input->getOption('format'), $input->getOption('show-ignored-violations'));
     if ('txt' === $input->getOption('format') && OutputInterface::VERBOSITY_VERBOSE > $output->getVerbosity()) {
         $output->writeln('');
         $output->writeln(sprintf('Run <comment>%s %s %s -v</comment> to get the full report', $_SERVER['PHP_SELF'], 'analysis', $projectUuid));
     }
 }
开发者ID:sensiolabs,项目名称:insight,代码行数:33,代码来源:AnalyzeCommand.php


示例5: test

 public function test()
 {
     $i = (int) $this->input->get('i');
     @usleep(1000 - i * 250);
     $this->output->set_header('Content-type: text/html; charset=utf-8', true);
     $this->output->set_output('result ' . $i);
 }
开发者ID:acamboy,项目名称:starter-public-edition-3,代码行数:7,代码来源:Ajax_queue_controller.php


示例6: sendWPRCRequestWithRetries

 /**
  * Send request to the WPRC server only with retries
  * 
  * @param string method
  * @param mixed arguments to send
  */
 public function sendWPRCRequestWithRetries($method, $args, $timeout = 5)
 {
     $url = WPRC_SERVER_URL;
     $send_result = false;
     $failed = 0;
     $timer = get_transient('wprc_report_failed_timer');
     if ($timer != false && $timer != '' && $timer != null) {
         $timer = intval($timer);
     } else {
         $timer = 0;
     }
     $timenow = time();
     if ($timer - $timenow > 0) {
         return false;
     }
     // discard report
     while ($send_result === false && $failed < 2) {
         $send_result = $this->sendRequest($method, $url, $args, $timeout);
         if ($send_result === false) {
             $failed++;
             if ($failed < 2) {
                 usleep(rand(100, 300));
             }
             // wait 1 to 3 seconds
         }
     }
     if ($send_result === false) {
         set_transient('wprc_report_failed_timer', time() + 5 * 60 * 60);
     } else {
         // reset flags
         set_transient('wprc_report_failed_timer', 0);
     }
     return $send_result;
 }
开发者ID:adisonc,项目名称:MaineLearning,代码行数:40,代码来源:wprc-repository-connector.php


示例7: lock

 /**
  * 上锁
  *
  * @param string $key
  * @param bool $wouldblock 是否堵塞
  *
  * @return mixed
  */
 public function lock($key, $wouldblock = false)
 {
     if (empty($key)) {
         return false;
     }
     if (isset(self::$lockCache[$key])) {
         //FileLock不支持设置过期时间
         return true;
     }
     $fileName = $this->getFileName($key);
     if (!($fp = fopen($fileName, 'w+'))) {
         return false;
     }
     if (flock($fp, LOCK_EX | LOCK_NB)) {
         self::$lockCache[$fileName] = $fp;
         return true;
     }
     //非堵塞模式
     if (!$wouldblock) {
         return false;
     }
     //堵塞模式
     do {
         usleep(200);
     } while (!flock($fp, LOCK_EX | LOCK_NB));
     self::$lockCache[$fileName] = $fp;
     return true;
 }
开发者ID:im286er,项目名称:cmlphp,代码行数:36,代码来源:File.php


示例8: login

 /**
  * Handle connecting and logging into Magrathea. Returns 0 on success.
  * @param $hostname The hostname to connect to
  * @param $username Username
  * @param $password Password
  */
 function login($hostname, $username, $password)
 {
     $r = "";
     $code = "";
     $msg = "";
     $ret = $this->connect($hostname, $this->port, $username, $password);
     if ($ret == 0) {
         $ret = false;
         $this->getresponse($r);
         if ($this->use_usleep) {
             usleep($this->sleeptime);
         } else {
             sleep(1);
         }
         $this->loginprompt = $r;
         $this->docommand("AUTH {$username} {$password}", $r);
         if ($this->parse_response($r, $code, $msg)) {
             if ($code == 0) {
                 # Logged in!
                 $ret = true;
             }
         }
     } else {
         $ret = false;
     }
     return $ret;
 }
开发者ID:sluther,项目名称:agilebill,代码行数:33,代码来源:magrathea.inc.php


示例9: grabData

 public function grabData($url)
 {
     $pageNum = 2;
     $nextUrl = $url;
     do {
         $content = $this->getContent($nextUrl, 'windows-1251');
         $saw = $this->getNokogiri($content);
         $nextUrl = $saw->get('a.next')->toArray();
         if (array_key_exists('0', $nextUrl)) {
             $nextUrl = $nextUrl[0]['href'];
             $nextUrl = preg_replace("#page_\\d+\\.#uis", "page_{$pageNum}.", $nextUrl);
             if (strpos($content, "page_{$pageNum}.html") === false) {
                 $nextUrl = null;
             }
         } else {
             $nextUrl = null;
         }
         $pageNum++;
         $detailInfoUrl = $this->grabList($content);
         foreach ($detailInfoUrl as $detailUrl) {
             echo "Item: {$detailUrl}\n";
             $content = $this->getContent($detailUrl, 'windows-1251');
             $this->grabItem($detailUrl, $content);
         }
         echo "Dir: {$nextUrl}\n";
         usleep(500000);
     } while ($nextUrl);
 }
开发者ID:sb15,项目名称:legacy-library,代码行数:28,代码来源:Gobars.php


示例10: pulse

 public static function pulse($pin, $miliseconds, $state)
 {
     Gpio::write($pin, $state);
     usleep($miliseconds);
     $state = $state == 1 ? 0 : 1;
     Gpio::write($pin, $state);
 }
开发者ID:kofeve,项目名称:yana-server,代码行数:7,代码来源:Gpio.class.php


示例11: write

 /**
  * @return SocketOutputStream
  **/
 public function write($buffer)
 {
     if ($buffer === null) {
         return $this;
     }
     $totalBytes = strlen($buffer);
     try {
         $writtenBytes = $this->socket->write($buffer);
         if ($writtenBytes === false) {
             throw new IOTimedOutException('writing to socket timed out');
         }
         $i = 0;
         while ($writtenBytes < $totalBytes && $i < self::WRITE_ATTEMPTS) {
             // 0.1s sleep insurance if something wrong with socket
             usleep(100000);
             $remainingBuffer = substr($buffer, $writtenBytes);
             // NOTE: ignoring timeouts here
             $writtenBytes += $this->socket->write($remainingBuffer);
             ++$i;
         }
     } catch (NetworkException $e) {
         throw new IOException($e->getMessage());
     }
     if ($writtenBytes < $totalBytes) {
         throw new IOException('connection is too slow or buffer is too large?');
     }
     return $this;
 }
开发者ID:onphp-framework,项目名称:onphp-framework,代码行数:31,代码来源:SocketOutputStream.class.php


示例12: uploadAction

 public function uploadAction()
 {
     $this->_helper->viewRenderer->setNoRender(true);
     $this->view->layout()->disableLayout(true);
     $adapter = new Zend_ProgressBar_Adapter_JsPush(array('updateMethodName' => 'Zend_ProgressBar_Update', 'finishMethodName' => 'Zend_ProgressBar_Finish'));
     $progressBar = new Zend_ProgressBar($adapter, 0, 100);
     for ($i = 1; $i <= 100; $i++) {
         if ($i < 20) {
             $text = 'Just beginning';
         } else {
             if ($i < 50) {
                 $text = 'A bit done';
             } else {
                 if ($i < 80) {
                     $text = 'Getting closer';
                 } else {
                     $text = 'Nearly done';
                 }
             }
         }
         $progressBar->update($i, $text);
         usleep(100000);
     }
     $progressBar->finish();
 }
开发者ID:rlecellier,项目名称:basezf,代码行数:25,代码来源:FormController.php


示例13: wait_reply

 private function wait_reply($expected_result, $timeout)
 {
     $this->debugmsg("Waiting {$timeout} seconds for expected result");
     //Clear buffer
     $this->buffer = '';
     //Set timeout
     $timeoutat = time() + $timeout;
     //Loop until timeout reached (or expected result found)
     do {
         $this->debugmsg('Now: ' . time() . ", Timeout at: {$timeoutat}");
         $buffer = fread($this->fp, 1024);
         $this->buffer .= $buffer;
         usleep(200000);
         //0.2 sec
         $this->debugmsg("Received: {$buffer}");
         //Check if received expected responce
         if (preg_match('/' . preg_quote($expected_result, '/') . '$/', $this->buffer)) {
             $this->debugmsg('Found match');
             return true;
             //break;
         } else {
             if (preg_match('/\\+CMS ERROR\\:\\ \\d{1,3}\\r\\n$/', $this->buffer)) {
                 return false;
             }
         }
     } while ($timeoutat > time());
     $this->debugmsg('Timed out');
     return false;
 }
开发者ID:Admiralmj23,项目名称:E2PsSMS,代码行数:29,代码来源:samplesms.php


示例14: flushPause

function flushPause($pause = 0)
{
    echo ob_get_clean();
    @ob_flush();
    flush();
    usleep($pause * 1000000);
}
开发者ID:sebmarkbage,项目名称:mootools-core,代码行数:7,代码来源:DOMReady.php


示例15: send

 public function send()
 {
     $nk = Nosql::NK_ASYNC_EMAIL_QUEUE;
     $beginTime = time();
     do {
         do {
             $rawMsg = Nosql::lPop($nk);
             if ($rawMsg === false || !isset($rawMsg[0])) {
                 break;
             }
             $data = json_decode($rawMsg, true);
             $ret = SendMail::sendmail($data['toList'], $data['title'], $data['desc']);
             if ($ret === false) {
                 if (isset($data['retry'])) {
                     continue;
                     // drop it
                 } else {
                     $data['retry'] = 1;
                     Nosql::lPush($nk, json_encode($data));
                 }
             }
         } while (true);
         if (time() - $beginTime > 30) {
             // 30秒脚本重新执行一次
             break;
         }
         usleep(200000);
     } while (true);
 }
开发者ID:noikiy,项目名称:php,代码行数:29,代码来源:SendMailController.php


示例16: getsock

function getsock($port)
{
    $socket = null;
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false || $socket === null) {
        $error = socket_strerror(socket_last_error());
        $msg = "socket create({$port}) failed";
        echo "ERR: {$msg} '{$error}'\n";
        return NULL;
    }
    socket_set_nonblock($socket);
    $res = socket_connect($socket, API_HOST, $port);
    $timeout = 50;
    while ($res === false && $timeout > 0) {
        $err = socket_last_error($socket);
        echo ".";
        if ($timeout > 1 && ($err == 115 || $err == 114)) {
            $timeout--;
            usleep(50);
            $res = socket_connect($socket, API_HOST, $port);
            continue;
        }
        $error = socket_strerror($err);
        $msg = "socket connect({$port}) failed";
        echo "ERR: {$msg} '{$error}'\n";
        socket_close($socket);
        return NULL;
    }
    socket_set_block($socket);
    return $socket;
}
开发者ID:Encel-US,项目名称:cpuminer-multi,代码行数:31,代码来源:local-sample.php


示例17: adjust

 /**
  *
  */
 public function adjust()
 {
     $frameTicks = $this->getElapsed();
     if ($frameTicks < 1) {
         usleep(1000 - $frameTicks);
     }
 }
开发者ID:scipper,项目名称:applicationserver,代码行数:10,代码来源:Timer.php


示例18: runRequest

 /**
  * Runs http calls.
  * 
  * @param  string $method  
  * @param  string $url     
  * @param  array $content 
  * @param  boolean $auth    
  * @return object
  */
 public static function runRequest($method, $url, $content, $auth)
 {
     $guzzle = new GuzzleClient(['http_errors' => false, 'allow_redirects' => true]);
     $url = self::$base_url . "/{$url}";
     $headers = ['User-Agent' => self::getUserAgent(), 'Content-Type' => 'application/json'];
     if (!$auth) {
         $headers['authorization'] = DISCORD_TOKEN;
     }
     $done = false;
     $finalRes = null;
     while (!$done) {
         $content = is_null($content) ? null : json_encode($content);
         $request = new Request($method, $url, $headers, $content);
         $response = $guzzle->send($request);
         // Rate limiting
         if ($response->getStatusCode() == 429) {
             $tts = $response->getHeader('Retry-After') * 1000;
             usleep($tts);
             continue;
         }
         // Not good!
         if ($response->getStatusCode() < 200 || $response->getStatusCode() > 226) {
             self::handleError($response->getStatusCode(), $response->getReasonPhrase());
             continue;
         }
         $done = true;
         $finalRes = $response;
     }
     return json_decode($finalRes->getBody());
 }
开发者ID:jamiebatch452,项目名称:DiscordPHP,代码行数:39,代码来源:Guzzle.php


示例19: __invoke

 /**
  * Sends an HTTP request.
  *
  * @param RequestInterface $request Request to send.
  * @param array            $options Request transfer options.
  *
  * @return PromiseInterface
  */
 public function __invoke(RequestInterface $request, array $options)
 {
     // Sleep if there is a delay specified.
     if (isset($options['delay'])) {
         usleep($options['delay'] * 1000);
     }
     $startTime = isset($options['on_stats']) ? microtime(true) : null;
     try {
         // Does not support the expect header.
         $request = $request->withoutHeader('Expect');
         // Append a content-length header if body size is zero to match
         // cURL's behavior.
         if (0 === $request->getBody()->getSize()) {
             $request = $request->withHeader('Content-Length', 0);
         }
         return $this->createResponse($request, $options, $this->createStream($request, $options), $startTime);
     } catch (\InvalidArgumentException $e) {
         throw $e;
     } catch (\Exception $e) {
         // Determine if the error was a networking error.
         $message = $e->getMessage();
         // This list can probably get more comprehensive.
         if (strpos($message, 'getaddrinfo') || strpos($message, 'Connection refused') || strpos($message, "couldn't connect to host")) {
             $e = new ConnectException($e->getMessage(), $request, $e);
         }
         $e = RequestException::wrapException($request, $e);
         $this->invokeStats($options, $request, $startTime, null, $e);
         return new RejectedPromise($e);
     }
 }
开发者ID:sunkangtaichi,项目名称:PHPAPPLISTION_START,代码行数:38,代码来源:StreamHandler.php


示例20: testUpdateMessage

 /**
  * @depends testCreateMessage
  */
 function testUpdateMessage($stack)
 {
     try {
         $message = array('title' => $this->getRandom(100), 'message' => $this->getRandom(256), 'deviceType' => 'ios', 'deviceToken' => $this->hexadecimal(64), 'userId' => $this->getRandom(16), 'group' => $this->getRandom(64), 'lang' => 'en', 'deliveryDateTime' => date(DATE_RFC1123, strtotime('15 min')), 'deliveryExpiration' => '1 day', 'badgeIncrement' => false, 'contentAvailable' => false);
         /** @var Model $model */
         $model = $this->getClient()->updateMessage(array_merge(array('pushId' => $stack['PushId']), $message));
         $this->assertNotEmpty($model['result']['updatedDate']);
         usleep(10000);
         $model = $this->getClient()->getMessage(array('pushId' => $stack['PushId']));
         $updated = $model['result'];
         foreach (array('title', 'message', 'deviceType', 'deviceToken', 'userId', 'group', 'lang', 'deliveryExpiration') as $name) {
             $this->assertArrayHasKey($name, $updated);
             $this->assertEquals($message[$name], $updated[$name], sprintf('assertEquals %s', $name));
         }
         $this->assertArrayHasKey('deliveryDateTime', $updated);
         $this->assertEquals($updated['deliveryDateTime'], date('Y-m-d H:i:00', strtotime('15 min')));
         $this->assertArrayHasKey('badgeIncrement', $updated);
         $this->assertEquals(false, $updated['badgeIncrement']);
         $this->assertArrayHasKey('contentAvailable', $updated);
         $this->assertEquals(false, $updated['contentAvailable']);
     } catch (\Guzzle\Http\Exception\BadResponseException $e) {
         $response = $e->getResponse()->json();
         $this->fail(sprintf('Unexpected exception: %s', $response['error_message']));
     } catch (\Exception $e) {
         throw $e;
     }
     return $stack;
 }
开发者ID:sonicmoov,项目名称:hmb-sdk-php,代码行数:31,代码来源:PushClientTest.php



注:本文中的usleep函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP usort函数代码示例发布时间:2022-05-23
下一篇:
PHP usingLog函数代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap