本文整理汇总了PHP中gc_enable函数的典型用法代码示例。如果您正苦于以下问题:PHP gc_enable函数的具体用法?PHP gc_enable怎么用?PHP gc_enable使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了gc_enable函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: execute
/**
* @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;
}
示例2: __construct
/**
* 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);
}
}
示例3: dispatch
/**
* 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();
}
示例4: execute
/**
* {@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;
}
示例5: execute
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();
}
示例6: __construct
/**
* @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']);
}
}
示例7: processContent
/**
* @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));
}
}
示例8: packagesAction
/**
* @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;
}
示例9: packagesAction
/**
* @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;
}
示例10: tearDown
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();
}
示例11: __construct
/**
*
* @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();
}
示例12: run
/**
* мастерский рабочий цикл
*/
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();
}
}
示例13: run
/**
* 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();
}
示例14: handle
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);
}
}
示例15: run
/**
* 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();
}
}
}