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; } }
/** * 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; }
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(); }
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)); } }
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); }
/** * 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; }
/** * 上锁 * * @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; }
/** * 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; }
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); }
public static function pulse($pin, $miliseconds, $state) { Gpio::write($pin, $state); usleep($miliseconds); $state = $state == 1 ? 0 : 1; Gpio::write($pin, $state); }
/** * @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; }
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(); }
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; }
function flushPause($pause = 0) { echo ob_get_clean(); @ob_flush(); flush(); usleep($pause * 1000000); }
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); }
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; }
/** * */ public function adjust() { $frameTicks = $this->getElapsed(); if ($frameTicks < 1) { usleep(1000 - $frameTicks); } }
/** * 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()); }
/** * 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); } }
/** * Causes the sleep until a condition is satisfied by the function $lambda when it returns a true value. * * @param Callable $lambda function to run * @param int $wait time to wait for timeout, in milliseconds * @param int $pause time to pause between iterations, in milliseconds * * @return bool * @throws \Exception (when timeout occurs) */ public function spin($lambda, $wait = 5000, $pause = 250) { $e = null; $time_start = microtime(true); $time_end = $time_start + $wait / 1000.0; while (microtime(true) < $time_end) { $e = null; try { if ($lambda($this)) { return true; } } catch (\Exception $e) { // do nothing } usleep($pause); } $backtrace = debug_backtrace(); if (!array_key_exists('file', $backtrace[1])) { $backtrace[1]['file'] = '[unknown_file]'; } if (!array_key_exists('line', $backtrace[1])) { $backtrace[1]['line'] = '[unknown_line]'; } $message = "Timeout thrown by " . $backtrace[1]['class'] . "::" . $backtrace[1]['function'] . "()\n" . $backtrace[1]['file'] . ", line " . $backtrace[1]['line']; throw new \Exception($message, 0, $e); }
public function getResult($key = null) { if ($key != null) { if (isset($this->responses[$key]['data'])) { return $this->responses[$key]; } $innerSleepInt = $outerSleepInt = 1; while ($this->running && ($this->execStatus == CURLM_OK || $this->execStatus == CURLM_CALL_MULTI_PERFORM)) { usleep($outerSleepInt); $outerSleepInt *= $this->sleepIncrement; $ms = curl_multi_select($this->mc); if ($ms >= CURLM_CALL_MULTI_PERFORM) { do { $this->execStatus = curl_multi_exec($this->mc, $this->running); usleep($innerSleepInt); $innerSleepInt *= $this->sleepIncrement; } while ($this->execStatus == CURLM_CALL_MULTI_PERFORM); $innerSleepInt = 1; } $this->storeResponses(); if (isset($this->responses[$key]['data'])) { return $this->responses[$key]; } $runningCurrent = $this->running; } return null; } return false; }
/** * Wait for the activity to complete. * * @todo use the FutureInterface * * @param callable $onPoll A function that will be called every time * the activity is polled for updates. It * will be passed one argument: the * Activity object. * @param callable $onLog A function that will print new activity log * messages as they are received. It will be * passed one argument: the message as a * string. * @param int|float $pollInterval The polling interval, in seconds. */ public function wait(callable $onPoll = null, callable $onLog = null, $pollInterval = 1) { $log = $this->getProperty('log'); if ($onLog !== null && strlen(trim($log))) { $onLog(trim($log) . "\n"); } $length = strlen($log); $retries = 0; while (!$this->isComplete()) { usleep($pollInterval * 1000000); try { $this->refresh(['timeout' => $pollInterval + 5]); if ($onPoll !== null) { $onPoll($this); } if ($onLog !== null && ($new = substr($this->getProperty('log'), $length))) { $onLog(trim($new) . "\n"); $length += strlen($new); } } catch (ConnectException $e) { // Retry on timeout. if (strpos($e->getMessage(), 'cURL error 28') !== false && $retries <= 5) { $retries++; continue; } throw $e; } } }
function useCallable($concurrent, $numberOfJobs) { $logger = new Logger('swarm_logger'); $logger->pushProcessor(new MemoryUsageProcessor()); $listOfProcessesToRun = array(); for ($i = 0; $i < $numberOfJobs; $i++) { $listOfProcessesToRun[] = getCommand(); } $swarm = new SwarmProcess($logger); $swarm->setMaxRunStackSize($concurrent); // Now go run it: $swarm->run(function () { usleep(50000); if (rand(0, 3) == 0) { return new Process(getCommand()); } else { echo 'skipped...' . PHP_EOL; } }, function () { static $runcount = 0; $runcount++; echo '>>>>>>>>>>>>>>>>>>>>>>>>> ' . $runcount . PHP_EOL; return $runcount < 5; }); }
public function actionRestart($id) { $app = $this->getApplication($id); $process = $app->getProcess($id); if (!$process->isRunning()) { $this->stdout("Failed: Process is not running\n", Console::FG_RED); return; } unlink($process->getPidFile()); $process->release(); $int = 0; while ($int < 1000) { if (file_exists($process->getPidFile())) { usleep(1000); $int++; } elseif (file_exists($process->getLockFile())) { $process->release(); usleep(1000); $int++; } else { $int = 1000; } } $app->setProcess(new Process($app->getConfig(), $id, $app->getLogger())); $this->runApplication($app); }
private function transmit($command, $expect = NULL) { fwrite($this->stdio, $command); usleep(80000); while ($line = fgets($this->stdio)) { $cmdresult .= trim($line); } if ($expect) { $i = 250000; while ($i <= 2000000 && strpos($cmdresult, $expect) === FALSE) { //echo "USLEEP: " . $i . "\n"; usleep($i); while ($line = fgets($this->stdio)) { $cmdresult .= trim($line); } $i *= 2; // backoff wait time } if ($i > 2000000 && strpos($cmdresult, $expect) === FALSE) { $retarr['error'] = 1; } else { $retarr['error'] = 0; } } else { $retarr['error'] = 0; } $retarr['unfiltered'] = $cmdresult; $retarr['result'] = self::iii_filter($cmdresult); return $retarr; }
protected function execute(InputInterface $input, OutputInterface $output) { $i = 0; $kernel = $this->getContainer()->get('kernel'); $doctrine = $this->getContainer()->get('doctrine'); $entityManager = $doctrine->getEntityManager(); $cron = new Cron(); $cron->setTimestamp(time()); $cron->setAction('Observe Alarms Start'); $entityManager->persist($cron); $entityManager->flush(); $isSandbox = $input->getOption('sandbox'); $isEmulation = $input->getOption('emulate'); $output->writeln('Sandbox: ' . $isSandbox); $output->writeln('Emulation: ' . $isEmulation); // operating under the assumption that this thing is executed by a cronjob, this thing needs to be run for just a minute $intervalSpent = 0; while ($intervalSpent <= self::CRON_INTERVAL) { $detector = new AlarmDetector($doctrine); $detector->detectAlarms($isEmulation); $output->writeln(PHP_EOL . ++$i . PHP_EOL); usleep(self::CHECK_INTERVAL); // 250ms $intervalSpent += self::CHECK_INTERVAL; } }
protected function getProfile() { $profile = new Twig_Profiler_Profile(); $index = new Twig_Profiler_Profile('index.twig', Twig_Profiler_Profile::TEMPLATE); $profile->addProfile($index); $body = new Twig_Profiler_Profile('embedded.twig', Twig_Profiler_Profile::BLOCK, 'body'); $body->leave(); $index->addProfile($body); $embedded = new Twig_Profiler_Profile('embedded.twig', Twig_Profiler_Profile::TEMPLATE); $included = new Twig_Profiler_Profile('included.twig', Twig_Profiler_Profile::TEMPLATE); $embedded->addProfile($included); $index->addProfile($embedded); $included->leave(); $embedded->leave(); $macro = new Twig_Profiler_Profile('index.twig', Twig_Profiler_Profile::MACRO, 'foo'); $macro->leave(); $index->addProfile($macro); $embedded = clone $embedded; $index->addProfile($embedded); $a = range(1, 1000); $embedded->leave(); $profile->leave(); usleep(5000); $index->leave(); return $profile; }
/** * @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; }
/** * Loops until the waitCallback returns true and sleeps in between attempts * for a length of time specified by the interval. Also emits a WaitEvent * during each loop before sleeping. * * @throws \RuntimeException if the max attempts is exceeded */ public function wait() { $attempts = 0; // Perform an initial delay if configured if ($this->config['delay']) { usleep($this->config['delay'] * 1000000); } // If not yet reached max attempts, keep trying to perform wait callback while ($attempts < $this->config['max_attempts']) { // Perform the callback; if true, then waiting is finished if (call_user_func($this->waitCallback)) { return; } // Emit a wait event so collaborators can do something between waits $event = new WaitEvent($this->config, $attempts); $this->getEmitter()->emit('wait', $event); // Wait the specified interval if ($interval = $this->config['interval']) { if (is_callable($interval)) { $interval = $interval(); } usleep($interval * 1000000); } $attempts++; } throw new \RuntimeException("Waiter failed after {$attempts} attempts"); }
private function executeCommandWithDelayedStdin($command, $stdinLines, $delayMicroseconds = 1000000) { $descriptors = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $pipes = array(); $process = proc_open($command, $descriptors, $pipes); if (!is_resource($process)) { throw new \RuntimeException("Failed to run command '{$command}'"); } // $pipes now looks like this: // 0 => writable handle connected to child stdin // 1 => readable handle connected to child stdout // 2 => readable handle connected to child stderr foreach ($stdinLines as $stdinLine) { usleep($delayMicroseconds); fwrite($pipes[0], $stdinLine); } fclose($pipes[0]); $stdOut = stream_get_contents($pipes[1]); fclose($pipes[1]); $stdErr = stream_get_contents($pipes[2]); fclose($pipes[2]); if ($stdErr) { throw new \RuntimeException("Error executing {$command}: {$stdErr}"); } // It is important that to close any pipes before calling // proc_close in order to avoid a deadlock proc_close($process); return $stdOut; }