/** * @inheritdoc */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('PHPMetrics by Jean-François Lépine <https://twitter.com/Halleck45>'); $output->writeln(''); // config $configFactory = new ConfigFactory(); $config = $configFactory->factory($input); // files if (null === $config->getPath()->getBasePath()) { throw new \LogicException('Please provide a path to analyze'); } // files to analyze $finder = new Finder($config->getPath()->getExtensions(), $config->getPath()->getExcludedDirs(), $config->getPath()->isFollowSymlinks() ? Finder::FOLLOW_SYMLINKS : null); // prepare structures $bounds = new Bounds(); $collection = new \Hal\Component\Result\ResultCollection(); $aggregatedResults = new \Hal\Component\Result\ResultCollection(); // execute analyze $queueFactory = new QueueFactory($input, $output, $config); $queue = $queueFactory->factory($finder, $bounds); gc_disable(); $queue->execute($collection, $aggregatedResults); gc_enable(); $output->writeln('<info>done</info>'); // evaluation of success $evaluator = new Evaluator($collection, $aggregatedResults, $bounds); $result = $evaluator->evaluate($config->getFailureCondition()); // fail if failure-condition is realized return $result->isValid() ? 1 : 0; }
/** * Making the class non-abstract with a protected constructor does a better * job of preventing instantiation than just marking the class as abstract. * * @see start() */ public function __construct(array $configs) { // Quickly initialize some defaults like usePEAR // by adding the $premature flag $this->_optionsInit(true); $this->setOptions($configs); if ($this->opt('logPhpErrors')) { set_error_handler(array('self', 'phpErrors'), E_ALL); } // Check the PHP configuration if (!defined('SIGHUP')) { trigger_error('PHP is compiled without --enable-pcntl directive', E_USER_ERROR); } // Check for CLI if (php_sapi_name() !== 'cli') { trigger_error('You can only create daemon from the command line (CLI-mode)', E_USER_ERROR); } // Check for POSIX if (!function_exists('posix_getpid')) { trigger_error('PHP is compiled without --enable-posix directive', E_USER_ERROR); } // Enable Garbage Collector (PHP >= 5.3) if (function_exists('gc_enable')) { gc_enable(); } // Initialize & check variables if (false === $this->_optionsInit(false)) { if (is_object($this->_option) && is_array($this->_option->errors)) { foreach ($this->_option->errors as $error) { $this->notice($error); } } trigger_error('Crucial options are not set. Review log:', E_USER_ERROR); } }
/** * Registered callback function for the WordPress Importer * * Manages the three separate stages of the CSV import process */ function dispatch() { $this->header(); if (!empty($_POST['delimiter'])) { $this->delimiter = stripslashes(trim($_POST['delimiter'])); } if (!$this->delimiter) { $this->delimiter = ','; } $step = empty($_GET['step']) ? 0 : (int) $_GET['step']; switch ($step) { case 0: $this->greet(); break; case 1: check_admin_referer('import-upload'); if ($this->handle_upload()) { if ($this->id) { $file = get_attached_file($this->id); } else { $file = ABSPATH . $this->file_url; } add_filter('http_request_timeout', array($this, 'bump_request_timeout')); if (function_exists('gc_enable')) { gc_enable(); } @set_time_limit(0); @ob_flush(); @flush(); $this->import($file); } break; } $this->footer(); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $force = (bool) $input->getOption('force'); $verbose = (bool) $input->getOption('verbose'); $deployLock = $this->getContainer()->getParameter('kernel.cache_dir') . '/deploy.globallock'; if (file_exists($deployLock)) { if ($verbose) { $output->writeln('Aborting, ' . $deployLock . ' file present'); } return; } $doctrine = $this->getContainer()->get('doctrine'); if ($force) { $packages = $doctrine->getManager()->getConnection()->fetchAll('SELECT id FROM package ORDER BY id ASC'); } else { $packages = $doctrine->getRepository('PackagistWebBundle:Package')->getStalePackagesForDumping(); } $ids = array(); foreach ($packages as $package) { $ids[] = $package['id']; } $lock = new LockHandler('packagist_package_dumper'); ini_set('memory_limit', -1); gc_enable(); // another dumper is still active if (!$lock->lock()) { if ($verbose) { $output->writeln('Aborting, another dumper is still active'); } return; } $result = $this->getContainer()->get('packagist.package_dumper')->dump($ids, $force, $verbose); $lock->release(); return $result ? 0 : 1; }
protected function execute(InputInterface $input, OutputInterface $output) { // Use all the memory ini_set('memory_limit', '-1'); gc_enable(); error_reporting(1); error_reporting(E_ALL); define('DISCORDPHP_STARTTIME', microtime(true)); define('BASEDIR', __DIR__); define('SOVEREIGN_CONFIG_FILE', realpath('./' . ltrim($input->getOption('configFile'), '/'))); // Init the container object $container = getContainer(); // Load the bot into the service container $container->share('app', Sovereign::class)->withArgument($container); try { // Init the bot $container->get('log')->addInfo('Sovereign is starting up..'); $bot = $container->get('app'); // Register the default plugins and services, and boot them. $container->addServiceProvider(SystemPluginServiceProvider::class); } catch (\Exception $e) { $container->get('log')->addError('An error occurred: ' . $e->getMessage()); die; } // Launch the bot $bot->run(); }
/** * @param String $name Unique name for the manager * @param array $config Config for the manager */ public function __construct($name, array $config = array()) { gc_enable(); $this->process = \Multitask\Process\Factory::getInstanceOsBased(); $this->spawner = new \Multitask\Spawner($this, $this->process); $this->workingDirectory = $this->pidFilename = $this->name = $name; $this->cache = new \Multitask\Cache(); if (isset($config['logger']) && $config['logger'] instanceof \Multitask\Log\Base) { $this->logger = $config['logger']; } else { $this->logger = new \Multitask\Log\Dummy(); } Error::setHandler($this->logger); Error::setName($name); foreach ($config as $key => $value) { if (array_key_exists($key, $this->config)) { $this->config[$key] = $value; } } if (!$this->config['filePath']) { $this->config['filePath'] = __DIR__ . '/Cache/'; } $this->fileHandler = new File($this->config['filePath']); if ($this->config['timeLimit'] !== false) { set_time_limit($this->config['timeLimit']); } if ($this->config['memoryLimit'] !== false) { ini_set('memory_limit', $this->config['memoryLimit']); } }
/** * @inheritdoc * @throws ContentProcessorException */ public function processContent(File $asset) { $path = $asset->getPath(); try { $parser = new \Less_Parser(['relativeUrls' => false, 'compress' => $this->appState->getMode() !== State::MODE_DEVELOPER]); $content = $this->assetSource->getContent($asset); if (trim($content) === '') { return ''; } $tmpFilePath = $this->temporaryFile->createFile($path, $content); gc_disable(); $parser->parseFile($tmpFilePath, ''); $content = $parser->getCss(); gc_enable(); if (trim($content) === '') { $errorMessage = PHP_EOL . self::ERROR_MESSAGE_PREFIX . PHP_EOL . $path; $this->logger->critical($errorMessage); throw new ContentProcessorException(new Phrase($errorMessage)); } return $content; } catch (\Exception $e) { $errorMessage = PHP_EOL . self::ERROR_MESSAGE_PREFIX . PHP_EOL . $path . PHP_EOL . $e->getMessage(); $this->logger->critical($errorMessage); throw new ContentProcessorException(new Phrase($errorMessage)); } }
/** * @Template() * @Route("/packages.json", name="packages", defaults={"_format" = "json"}) */ public function packagesAction(Request $req) { // fallback if any of the dumped files exist $rootJson = $this->container->getParameter('kernel.root_dir') . '/../web/packages_root.json'; if (file_exists($rootJson)) { return new Response(file_get_contents($rootJson)); } $rootJson = $this->container->getParameter('kernel.root_dir') . '/../web/packages.json'; if (file_exists($rootJson)) { return new Response(file_get_contents($rootJson)); } if ($req->getHost() === 'packagist.org') { $this->get('logger')->alert('packages.json is missing and the fallback controller is being hit'); return new Response('Horrible misconfiguration or the dumper script messed up', 404); } $em = $this->get('doctrine')->getManager(); gc_enable(); $packages = $em->getRepository('Packagist\\WebBundle\\Entity\\Package')->getFullPackages(); $notifyUrl = $this->generateUrl('track_download', array('name' => 'VND/PKG')); $data = array('notify' => str_replace('VND/PKG', '%package%', $notifyUrl), 'packages' => array()); foreach ($packages as $package) { $versions = array(); foreach ($package->getVersions() as $version) { $versions[$version->getVersion()] = $version->toArray(); $em->detach($version); } $data['packages'][$package->getName()] = $versions; $em->detach($package); } unset($versions, $package, $packages); $response = new Response(json_encode($data), 200); $response->setSharedMaxAge(120); return $response; }
/** * @Template() * @Route("/packages.json", name="packages", defaults={"_format" = "json"}) */ public function packagesAction() { // fallback if any of the dumped files exist $rootJson = $this->container->getParameter('kernel.root_dir') . '/../web/packages_root.json'; if (file_exists($rootJson)) { return new Response(file_get_contents($rootJson)); } $rootJson = $this->container->getParameter('kernel.root_dir') . '/../web/packages.json'; if (file_exists($rootJson)) { return new Response(file_get_contents($rootJson)); } $em = $this->get('doctrine')->getEntityManager(); gc_enable(); $packages = $em->getRepository('Packagist\\WebBundle\\Entity\\Package')->getFullPackages(); $notifyUrl = $this->generateUrl('track_download', array('name' => 'VND/PKG')); $data = array('notify' => str_replace('VND/PKG', '%package%', $notifyUrl), 'packages' => array()); foreach ($packages as $package) { $versions = array(); foreach ($package->getVersions() as $version) { $versions[$version->getVersion()] = $version->toArray(); $em->detach($version); } $data['packages'][$package->getName()] = $versions; $em->detach($package); } unset($versions, $package, $packages); $response = new Response(json_encode($data), 200); $response->setSharedMaxAge(120); return $response; }
protected function tearDown() { //Close & unsets if (is_object($this->em)) { $this->em->getConnection()->close(); $this->em->close(); } unset($this->em); unset($this->container); unset($this->kern); unset($this->client); //Nettoyage des mocks //http://kriswallsmith.net/post/18029585104/faster-phpunit $refl = new \ReflectionObject($this); foreach ($refl->getProperties() as $prop) { if (!$prop->isStatic() && 0 !== strpos($prop->getDeclaringClass()->getName(), 'PHPUnit_')) { $prop->setAccessible(true); $prop->setValue($this, null); } } //Nettoyage du garbage if (!gc_enabled()) { gc_enable(); } gc_collect_cycles(); //Parent parent::tearDown(); }
/** * * @param WebSoccer $websoccer request context. * @param DbConnection $db database connection- * @param I18n $i18n messages context. * @param string $jobId Job ID as defined at jobs.xml. * @param $errorOnAlreadyRunning boolean TRUE if error shall occur on init time when an instance of this job is already running. */ function __construct(WebSoccer $websoccer, DbConnection $db, I18n $i18n, $jobId, $errorOnAlreadyRunning = TRUE) { $this->_websoccer = $websoccer; $this->_db = $db; $this->_i18n = $i18n; $this->_id = $jobId; $xmlConfig = $this->getXmlConfig(); // check if another instance is running (consider timeout of 5 minutes) if ($errorOnAlreadyRunning) { $initTime = (int) $xmlConfig->attributes()->inittime; $now = $websoccer->getNowAsTimestamp(); $timeoutTime = $now - 5 * 60; if ($initTime > $timeoutTime) { throw new Exception('Another instance of this job is already running.'); } $this->replaceAttribute('inittime', $now); } $interval = (int) $xmlConfig->attributes()->interval; $this->_interval = $interval * 60; ignore_user_abort(TRUE); // run possibly forever set_time_limit(0); // enable garbage collection (in case it is disabled by default) gc_enable(); }
/** * мастерский рабочий цикл */ public function run() { try { static::log('starting master (PID ' . posix_getpid() . ')....'); //задаем приоритет процесса в ОС proc_nice($this->priority); //включаем сборщик циклических зависимостей gc_enable(); //выполняем функцию приложения до рабочего цикла call_user_func([$this->appl, 'baseOnRun']); //самый главный цикл while (TRUE) { if (TRUE === call_user_func([$this->appl, 'baseRun'])) { //прекращаем цикл break; } //ожидаем заданное время для получения сигнала операционной системы $this->sigwait(); //если сигнал был получен, вызываем связанную с ним функцию pcntl_signal_dispatch(); } } catch (\Exception $e) { $this->shutdown(); } }
/** * Runtime of Worker process. * @return void */ protected function run() { if (Daemon::$process instanceof Master) { Daemon::$process->unregisterSignals(); } EventLoop::init(); Daemon::$process = $this; if (Daemon::$logpointerAsync) { Daemon::$logpointerAsync->fd = null; Daemon::$logpointerAsync = null; } class_exists('Timer'); if (Daemon::$config->autogc->value > 0) { gc_enable(); } else { gc_disable(); } $this->prepareSystemEnv(); $this->registerEventSignals(); FileSystem::init(); // re-init FileSystem::initEvent(); Daemon::openLogs(); $this->fileWatcher = new FileWatcher(); $this->IPCManager = Daemon::$appResolver->getInstanceByAppName('\\PHPDaemon\\IPCManager\\IPCManager'); if (!$this->IPCManager) { $this->log('cannot instantiate IPCManager'); } EventLoop::$instance->run(); }
public function handle() { if (Globals::RUNTIME_MODE_CLI !== App::environment(Globals::ENV_RUNTIME_MODE)) { throw new ConsoleException("Only run in command line mode"); } //加载Worker并为每个Worker创建一个子进程,然后进入休眠,当接收到信号量时,则执行相应的进程调度操作。 if (!function_exists("pcntl_signal")) { throw new ConsoleException("PHP does not appear to be compiled with the PCNTL extension.This is neccesary for daemonization"); } if (function_exists("gc_enable")) { gc_enable(); } $daemon = Daemon::make($_SERVER['argc'], $_SERVER['argv']); try { /** * @var $daemon Daemon */ if (isset($daemon)) { $daemon->start(); sleep(1); Console::line("Daemon [" . $daemon->getPID() . "] started."); } } catch (\Exception $ex) { throw new DaemonException($daemon->getName(), $ex->getMessage(), $ex); } }
/** * Runtime of Master process * @return void */ protected function run() { Daemon::$process = $this; $this->prepareSystemEnv(); class_exists('Timer'); // ensure loading this class gc_enable(); /* This line must be commented according to current libevent binding implementation. May be uncommented in future. */ //$this->eventBase = new \EventBase; if ($this->eventBase) { $this->registerEventSignals(); } else { $this->registerSignals(); } $this->workers = new Collection(); $this->collections['workers'] = $this->workers; $this->ipcthreads = new Collection(); $this->collections['ipcthreads'] = $this->ipcthreads; Daemon::$appResolver->preload(true); $this->callbacks = new StackCallbacks(); $this->spawnIPCThread(); $this->spawnWorkers(min(Daemon::$config->startworkers->value, Daemon::$config->maxworkers->value)); $this->timerCb = function ($event) use(&$cbs) { static $c = 0; ++$c; if ($c > 0xfffff) { $c = 1; } if ($c % 10 == 0) { gc_collect_cycles(); } if (!$this->lastMpmActionTs || microtime(true) - $this->lastMpmActionTs > $this->minMpmActionInterval) { $this->callMPM(); } if ($event) { $event->timeout(); } }; if ($this->eventBase) { // we are using libevent in Master Timer::add($this->timerCb, 1000000.0 * Daemon::$config->mpmdelay->value, 'MPM'); while (!$this->breakMainLoop) { $this->callbacks->executeAll($this); if (!$this->eventBase->dispatch()) { break; } } } else { // we are NOT using libevent in Master $lastTimerCall = microtime(true); while (!$this->breakMainLoop) { $this->callbacks->executeAll($this); if (microtime(true) > $lastTimerCall + Daemon::$config->mpmdelay->value) { call_user_func($this->timerCb, null); $lastTimerCall = microtime(true); } $this->sigwait(); } } }
private static function huffman_lookup_init() { gc_disable(); $encodingAccess = []; $terminals = []; foreach (self::HUFFMAN_CODE as $chr => $bits) { $len = self::HUFFMAN_CODE_LENGTHS[$chr]; for ($bit = 0; $bit < 8; $bit++) { $offlen = $len + $bit; $next =& $encodingAccess[$bit]; for ($byte = (int) (($offlen - 1) / 8); $byte > 0; $byte--) { $cur = \str_pad(\decbin($bits >> $byte * 8 - (0x30 - $offlen) % 8 & 0xff), 8, "0", STR_PAD_LEFT); if (isset($next[$cur]) && $next[$cur][0] != $encodingAccess[0]) { $next =& $next[$cur][0]; } else { $tmp =& $next; unset($next); $tmp[$cur] = [&$next, null]; } } $key = \str_pad(\decbin($bits & (1 << ($offlen - 1) % 8 + 1) - 1), ($offlen - 1) % 8 + 1, "0", STR_PAD_LEFT); $next[$key] = [null, $chr > 0xff ? "" : \chr($chr)]; if ($offlen % 8) { $terminals[$offlen % 8][] = [$key, &$next]; } else { $next[$key][0] =& $encodingAccess[0]; } } } $memoize = []; for ($off = 7; $off > 0; $off--) { foreach ($terminals[$off] as &$terminal) { $key = $terminal[0]; $next =& $terminal[1]; if ($next[$key][0] === null) { foreach ($encodingAccess[$off] as $chr => &$cur) { $next[($memoize[$key] ?? ($memoize[$key] = \str_pad($key, 8, "0", STR_PAD_RIGHT))) | $chr] = [&$cur[0], $next[$key][1] != "" ? $next[$key][1] . $cur[1] : ""]; } unset($next[$key]); } } } $memoize = []; for ($off = 7; $off > 0; $off--) { foreach ($terminals[$off] as &$terminal) { $next =& $terminal[1]; foreach ($next as $k => $v) { if (\strlen($k) != 1) { $next[$memoize[$k] ?? ($memoize[$k] = \chr(\bindec($k)))] = $v; unset($next[$k]); } } } } unset($tmp, $cur, $next, $terminals, $terminal); gc_enable(); gc_collect_cycles(); return $encodingAccess[0]; }
/** * Runtime of Master process * @return void */ public function run() { Daemon::$process = $this; $this->prepareSystemEnv(); class_exists('Timer'); // ensure loading this class gc_enable(); $this->eventBase = event_base_new(); $this->registerEventSignals(); FS::initEvent(); $this->fileWatcher = new FileWatcher(); $this->workers = new ThreadCollection(); $this->collections['workers'] = $this->workers; Daemon::$appResolver = (require Daemon::$config->path->value); $this->IPCManager = Daemon::$appResolver->getInstanceByAppName('IPCManager'); Daemon::$appResolver->preload(true); $this->callbacks = new SplStack(); $this->spawnWorkers(min(Daemon::$config->startworkers->value, Daemon::$config->maxworkers->value)); Timer::add(function ($event) use(&$cbs) { $self = Daemon::$process; static $c = 0; ++$c; if ($c > 0xfffff) { $c = 1; } if ($c % 10 == 0) { $self->workers->removeTerminated(true); gc_collect_cycles(); } else { $self->workers->removeTerminated(); } if (isset(Daemon::$config->mpm->value) && is_callable(Daemon::$config->mpm->value)) { call_user_func(Daemon::$config->mpm->value); } else { // default MPM $state = Daemon::getStateOfWorkers($self); if ($state) { $n = max(min(Daemon::$config->minspareworkers->value - $state['idle'], Daemon::$config->maxworkers->value - $state['alive']), Daemon::$config->minworkers->value - $state['alive']); if ($n > 0) { Daemon::log('Spawning ' . $n . ' worker(s).'); $self->spawnWorkers($n); event_base_loopbreak($self->eventBase); } $n = min($state['idle'] - Daemon::$config->maxspareworkers->value, $state['alive'] - Daemon::$config->minworkers->value); if ($n > 0) { Daemon::log('Stopping ' . $n . ' worker(s).'); $self->stopWorkers($n); } } } $event->timeout(); }, 1000000.0 * Daemon::$config->mpmdelay->value, 'MPM'); while (!$this->breakMainLoop) { while (!$this->callbacks->isEmpty()) { call_user_func($this->callbacks->shift(), $this); } event_base_loop($this->eventBase); } }
protected function iterate($seconds) { sleep($seconds); if (!gc_enabled()) { gc_enable(); } gc_collect_cycles(); }
/** * * @ignore */ function memory_and_gc($str) { $before = memory_get_usage(true); gc_enable(); $gcs = gc_collect_cycles(); $after = memory_get_usage(true); print "Memory usage at the {$str} : " . convert($before) . ". After GC: " . convert($after) . " and freed {$gcs} variables\n"; }
public function run() { $this->registerClassLoader(); gc_enable(); ini_set("memory_limit", -1); global $store; $store = []; }
/** * {@inheritdoc} */ public static function setUpBeforeClass() { // enables garbage collector because symfony/phpunit-bridge disables it. see: // see: https://github.com/symfony/symfony/pull/13398/files#diff-81bfee6017752d99d3119f4ddb1a09edR1 // see: https://github.com/symfony/symfony/pull/13398 (feature list) if (!gc_enabled()) { gc_enable(); } }
public function __construct() { $this->checkPcntl(); // Enable PHP 5.3 garbage collection if (function_exists('gc_enable')) { gc_enable(); $this->gc = gc_enabled(); } }
/** * @inheritdoc */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('PHPMetrics by Jean-François Lépine <https://twitter.com/Halleck45>'); $output->writeln(''); // config $configFactory = new ConfigFactory(); $config = $configFactory->factory($input); // files if (null === $config->getPath()->getBasePath()) { throw new \LogicException('Please provide a path to analyze'); } // files to analyze $finder = new Finder($config->getPath()->getExtensions(), $config->getPath()->getExcludedDirs(), $config->getPath()->isFollowSymlinks() ? Finder::FOLLOW_SYMLINKS : null); // prepare plugins $repository = new Repository(); foreach ($config->getExtensions()->getExtensions() as $filename) { if (!file_exists($filename) || !is_readable($filename)) { $output->writeln(sprintf('<error>Plugin %s skipped: not found</error>', $filename)); continue; } $plugin = (require_once $filename); $repository->attach($plugin); } $extensionService = new ExtensionService($repository); // prepare structures $bounds = new Bounds(); $collection = new ResultCollection(); $aggregatedResults = new ResultCollection(); // execute analyze $queueFactory = new QueueAnalyzeFactory($input, $output, $config, $extensionService); $queue = $queueFactory->factory($finder, $bounds); gc_disable(); $queue->execute($collection, $aggregatedResults); gc_enable(); $output->writeln(''); // provide data to extensions if (($n = sizeof($repository->all())) > 0) { $output->writeln(sprintf('%d %s. Executing analyzis', $n, $n > 1 ? 'plugins are enabled' : 'plugin is enabled')); $extensionService->receive($config, $collection, $aggregatedResults, $bounds); } // generating reports $output->writeln("Generating reports..."); $queueFactory = new QueueReportFactory($input, $output, $config, $extensionService); $queue = $queueFactory->factory($finder, $bounds); $queue->execute($collection, $aggregatedResults); $output->writeln('<info>Done</info>'); // evaluation of success $rule = $config->getFailureCondition(); if (null !== $rule) { $evaluator = new Evaluator($collection, $aggregatedResults, $bounds); $result = $evaluator->evaluate($rule); // fail if failure-condition is realized return $result->isValid() ? 1 : 0; } return 0; }
/** * Import is starting */ private function import_start() { if (function_exists('gc_enable')) { gc_enable(); } @set_time_limit(0); @ob_flush(); @flush(); @ini_set('auto_detect_line_endings', '1'); }
/** * Gc */ private function gc() { if (gc_enabled()) { gc_collect_cycles(); } else { gc_enable(); gc_collect_cycles(); gc_disable(); } }
/** * Echo current profiler output * * @param string $messageTemplate * * @return array */ protected function endCapturing($messageTemplate) { $time = microtime(true) - $this->startTime; $memory = memory_get_usage() - $this->startMemory; if (gc_enable()) { gc_collect_cycles(); } echo sprintf($messageTemplate, $time, $memory / 1024) . "\n"; return array('time' => $time, 'memory' => $memory); }
/** * In the constructor we'll simply initialise the earlier two properties, * respectivily with an array and the current timestamp. */ public static function Initialize() { self::$s_pStatistics = new \stdClass(); self::$s_pStatistics->Memory = 0; self::$s_pStatistics->Cycles = 0; self::$s_nLastCollect = time(); if (!gc_enabled()) { gc_enable(); } }
public static function clean($print = false) { gc_enable(); // Enable Garbage Collector if ($print) { AppLog::log(gc_collect_cycles() . " garbage cycles cleaned"); // # of elements cleaned up } gc_disable(); // Disable Garbage Collector }
/** * @inheritdoc */ public function __construct() { gc_enable(); $this->webSocketConnections = new WebSocketConnections(); $this->clientStorage = new ClientStorage(); $this->commandDispatcher = new Dispatcher(['clientStorage' => $this->clientStorage, 'commandNamespace' => 'StatusOnline\\Command\\Ready\\', 'commandFolder' => realpath(__DIR__ . '/../Command/Ready/')]); Debug::line('Author: ' . \StatusOnline\AUTHOR); Debug::line('GitHub: ' . \StatusOnline\GITHUB); Debug::line(); Debug::line(__CLASS__ . ': Started. Version: ' . \StatusOnline\VERSION); }
/** * @param Ratchet\MessageComponentInterface The Ratchet application stack to host * @param React\Socket\ServerInterface The React socket server to run the Ratchet application off of * @param React\EventLoop\LoopInterface The React looper to run the Ratchet application off of */ public function __construct(MessageComponentInterface $app, ServerInterface $socket, LoopInterface $loop) { gc_enable(); set_time_limit(0); ob_implicit_flush(); $this->loop = $loop; $this->app = $app; $socket->on('connection', array($this, 'handleConnect')); $this->handlers['data'] = array($this, 'handleData'); $this->handlers['end'] = array($this, 'handleEnd'); $this->handlers['error'] = array($this, 'handleError'); }