Example #1
0
#!/usr/bin/env php
<?php 
/**
 * @author pepov <*****@*****.**>
 */
require_once __DIR__ . '/../../bootstrap.php';
class SITF implements Ustream_Daemon_TaskFactory
{
    /**
     * @param Ustream_Daemon_Daemon $daemon
     *
     * @return Ustream_Daemon_Task
     */
    public function createTaskFor(Ustream_Daemon_Daemon $daemon)
    {
        return new Ustream_Daemon_CallbackTask(function () use($daemon) {
            $logger = new Ustream_Daemon_Logger($daemon);
            $logger->info(sprintf('Single instance'));
        });
    }
}
$config = new Ustream_Daemon_Config();
$config->runDir = __DIR__ . '/run';
$config->customDaemonUtilLogFile = __DIR__ . '/run/daemon_util.log';
$config->logDir = __DIR__ . '/run';
$config->context = \Ustream\DaemonTest\DaemonTestBase::CONTEXT;
$builder = new Ustream_Daemon_Builder($config);
$builder->setFileNameAsIdentifier(sprintf('singleinstance'))->sleepBetweenRuns(0.1)->build(new SITF())->start();
Example #2
0
    /**
     * @param string $runDir
     * @param string $context
     * @param string $iniDir
     * @param array  $listeners
     *
     * @return void
     *
     */
    public function runDaemon($runDir, $context, $iniDir, $listeners)
    {
        $opts = getopt('h::', array('defaults:', 'id:', 'factory:', 'sleep:', 'min-sleep:', 'instance:', 'config:', 'memory-limit:'));
        if (array_key_exists('h', $opts)) {
            echo <<<HELP
Usage:

\t  batch/daemon.php --id <name>

Required:
 --id <name>           Uniqe name that will be used in the pid/log file name and used to load default config

Default configuration:
 --config <file>       Custom configuration loaded from ini file

Factory method:
 --factory <callable>  Callable that will be used to create the Ustream_Daemon_Task implementation

Timing:
 --sleep <secs>        Sleep between subsequent task executions (minus the task runtime) 1 sec by default
 --min-sleep <secs>    Guaranteed sleep after each task 1 sec by default

Multi instance mode:
 --instance <num>      Run in multi instance mode and use <num> as instance number, starting from 0

PHP settings:
 --memory-limit <value>  Memory limit

HELP;
            exit;
        }
        try {
            if (!array_key_exists('id', $opts)) {
                throw new InvalidArgumentException('--id parameter missing');
            }
            if (array_key_exists('config', $opts)) {
                echo 'Using configuration from: ' . $opts['config'] . PHP_EOL;
                $opts = array_merge($this->loadDefaults($opts['config']), $opts);
            }
            $defaultConfig = sprintf($iniDir . '/%s.ini', $opts['id']);
            if (file_exists($defaultConfig)) {
                echo 'Using configuration from: ' . $defaultConfig . PHP_EOL;
                $opts = array_merge($this->loadDefaults($defaultConfig), $opts);
            }
            $defaultConfig = new Ustream_Daemon_Config();
            $defaults = array('sleep' => $defaultConfig->sleepBetweenRuns, 'min-sleep' => $defaultConfig->minimumSleep, 'memory-threshold' => $defaultConfig->memoryThreshold, 'log-dir' => $defaultConfig->logDir, 'common-log' => $defaultConfig->customDaemonUtilLogFile);
            $opts = array_merge($defaults, $opts);
            if (!array_key_exists('factory', $opts)) {
                throw new InvalidArgumentException('--factory parameter missing');
            }
            if (array_key_exists('memory-limit', $opts)) {
                ini_set('memory_limit', $opts['memory-limit']);
            }
            $builder = Ustream_Daemon_Builder::createDefault()->setId($opts['id'])->sleepBetweenRuns($opts['sleep'])->minumumSleep($opts['min-sleep'])->memoryThreshold($opts['memory-threshold'])->runDir($runDir)->logDir($opts['log-dir'])->commonLog($opts['common-log'])->context($context)->listeners($listeners);
            if (array_key_exists('instance', $opts)) {
                $builder->useMultipleInstances()->instanceNumber((int) $opts['instance']);
            }
            $daemon = $builder->buildUsingCallbackFactory($opts['factory']);
            echo 'Starting daemon if it\'s not already running' . PHP_EOL;
            echo sprintf('Sleep between runs / minimum sleep: %f / %f', $opts['sleep'], $opts['min-sleep']) . PHP_EOL;
            echo sprintf('Pid file: %s', $daemon->getPidFilePath()) . PHP_EOL;
            echo sprintf('Log file: %s', $daemon->getLogFilePath()) . PHP_EOL;
            if (file_exists($daemon->getPidFilePath())) {
                $message = sprintf('Pid file [%s] already exists', $daemon->getPidFilePath());
                trigger_error($message, E_USER_NOTICE);
                echo $message . PHP_EOL;
            }
            $daemon->start();
        } catch (Exception $e) {
            echo $e;
            exit(1);
        }
    }
Example #3
0
#!/usr/bin/env php
<?php 
/**
 * @author pepov <*****@*****.**>
 */
require_once __DIR__ . '/../../bootstrap.php';
class MITF implements Ustream_Daemon_MultiInstanceTaskFactory
{
    /**
     * @param Ustream_Daemon_Daemon $daemon
     * @param int $instanceId
     * @param int $instanceCount
     *
     * @return Ustream_Daemon_Task
     */
    public function create(Ustream_Daemon_Daemon $daemon, $instanceId, $instanceCount)
    {
        return new Ustream_Daemon_CallbackTask(function () use($instanceId, $instanceCount, $daemon) {
            $logger = new Ustream_Daemon_Logger($daemon);
            $logger->info(sprintf('Instance %d/%d', $instanceId, $instanceCount));
        });
    }
}
$config = new Ustream_Daemon_Config();
$config->runDir = __DIR__ . '/run';
$config->customDaemonUtilLogFile = __DIR__ . '/run/daemon_util.log';
$config->logDir = __DIR__ . '/run';
$config->context = \Ustream\DaemonTest\DaemonTestBase::CONTEXT;
$builder = new Ustream_Daemon_Builder($config);
$builder->setFileNameAsIdentifier('multiinstance')->sleepBetweenRuns(0.1)->buildMultiInstance(new MITF())->start();