public function init() { // Only use gearman implementation when WP_GEARS is defined and true if (!defined('WP_GEARS') || !WP_GEARS) { return false; } global $gearman_servers; if (!class_exists('GearmanClient') || !class_exists('GearmanWorker')) { return false; } if (defined('DOING_ASYNC') && DOING_ASYNC) { $this->_worker = new GearmanWorker(); $this->_client = new GearmanClient(); if (empty($gearman_servers)) { $this->_client->addServer(); return $this->_worker->addServer(); } else { $this->_client->addServers(implode(',', $gearman_servers)); return $this->_worker->addServers(implode(',', $gearman_servers)); } } else { $this->_client = new GearmanClient(); if (empty($gearman_servers)) { $this->_client->addServer(); } else { $this->_client->addServers(implode(',', $gearman_servers)); } // Supressing errors, because this will return true or false, depending on if we could connect & communicate return @$this->_client->ping('test'); } }
/** * Get the GearmanWorker instance * * @return GearmanWorker */ public function getWorkerConnection() { //we have a stored connection if (!$this->_gmWorker) { //Get the config, start the client object $_config = $this->_getConfiguration(); $this->_gmWorker = new GearmanWorker(); //add the servers to the client foreach ($_config as $_server) { $this->_gmWorker->addServer($_server['host'], $_server['port']); } } return $this->_gmWorker; }
public function work() { $config = $this->config->item('base_config'); $host = $config['gearman']['host']; $port = $config['gearman']['port']; $worker = new GearmanWorker(); $worker->addServer($host, $port); function send_request($job) { var_dump("scorpio"); include_once APPPATH . 'third_party/snoopy.php'; $snoopy = new Snoopy(); $data = json_decode($job->workload()); $method = $data->method; $url = $data->url; $params = $data->params; ${$method} = array(); foreach ($params as $key => $value) { ${$method}[$key] = $value; } $snoopy->submit($url, ${$method}); $result = $snoopy->results; return $result; } $worker->addFunction("send_request", "send_request"); while ($worker->work()) { } }
/** * 实现单例模式 * * @param array $config * @return GearmanWorker */ public static function getWorker($config) { $client = new GearmanWorker(); foreach ($config as $serverInfo) { $client->addServer($serverInfo['host'], $serverInfo['port']); } return $client; }
public function indexAction() { $config = App::instance()->config; $worker = new GearmanWorker(); $worker->addServer($config['gearman']['host'], $config['gearman']['port']); $worker->addFunction('delete_keys', array($this, 'deleteKeys')); $worker->addFunction('move_keys', array($this, 'moveKeys')); while ($worker->work()) { } }
function gearman_worker() { $gm = new GearmanWorker(); $gm->addServer(); $gm->addFunction('do_blacklist_checking', 'Monitor::do_blacklist_checking'); $gm->addFunction('process_pending_monitor', 'Monitor::process_pending_monitor'); while ($gm->work()) { echo $gm->returnCode(); } exit; }
/** * Get GearmanWorker object. * @param string $queueName Queue name * @return \GearmanWorker */ protected function getWorker($queueName) { if (!isset($this->workers[$queueName])) { $worker = new \GearmanWorker(); foreach ($this->servers as $server) { $worker->addServer($server); } $worker->addFunction($queueName, array($this, 'work')); $this->workers[$queueName] = $worker; } return $this->workers[$queueName]; }
public static function executeBgTasks() { $files = scandir(self::$uploads_dir); unset($files[0]); unset($files[1]); $jobs = array_values($files); foreach ($jobs as $key => $singleJob) { $worker = new GearmanWorker(); $worker->addServer(); $worker->addFunction('q' . $key, array(new MyClass(new GearmanJob()), 'csvHandler')); $worker->work(); } }
public function actionIndex() { $worker = new GearmanWorker(); $worker->addServer("219.232.243.98"); $worker->addFunction("sendMessage", function (GearmanJob $job) { $workload = json_decode($job->workload(), true); $phones = $workload['phones']; $content = $workload['content']; Yii::app()->smsClient->sendMessage($phones, $content); return true; }); while ($worker->work()) { } }
public static function run() { $lockAgent = new LockAgentWorker(); $worker = new \GearmanWorker(); $worker->addServer(); $worker->addFunction("findWithLock", array($lockAgent, "findWithLock")); $worker->addFunction("dqlWithLock", array($lockAgent, "dqlWithLock")); $worker->addFunction('lock', array($lockAgent, 'lock')); while ($worker->work()) { if ($worker->returnCode() != GEARMAN_SUCCESS) { echo "return_code: " . $worker->returnCode() . "\n"; break; } } }
public function run() { try { $gserver = $this->_configuration->gearman->server; $gport = $this->_configuration->gearman->port; $worker = new GearmanWorker(); $worker->addServer($gserver, $gport); $jobs = $this->_configuration->job; $worker->addFunction($jobs->sync_search, array($this, "syncSearch")); while ($worker->work()) { } } catch (Exception $ex) { Log::dumpLog("Uncaught exception: " . $ex->getMessage(), Log::ERR); } }
/** * The Gearman Worker processes requests passed to it from a Gearman * server. This class should be invoked as a daemon using the CLI * interface. Multiple instances can be created to handle multiple requests * asynchronously. * * // Initialize the Gearman Worker (in bootstrap) * Request_Async_Gearman::worker(); * exit(0); * * To create a daemon script, run the following command from your command * line. * * php /path/to/index.php * * @return void */ public static function worker() { $worker = new GearmanWorker(); $worker->addServer(); $worker->addFunction('request_async', array('Request_Async_Gearman', 'execute_request'), Request_Async_Gearman::$context); echo Request_Async_Gearman::$context . ': Starting worker.' . "\n"; while ($worker->work() or $worker->returnCode() == GEARMAN_IO_WAIT or $worker->returnCode() == GEARMAN_NO_JOBS) { if ($worker->returnCode() == GEARMAN_SUCCESS) { continue; } echo Request_Async_Gearman::$context . ': Waiting for next job...' . "\n"; if (!$worker->wait()) { if ($worker->returnCode() == GEARMAN_NO_ACTIVE_FDS) { usleep(100); continue; } } break; } echo Request_Async_Gearman::$context . ': Stopping worker.' . "\n"; echo Request_Async_Gearman::$context . ': Worker error' . $worker->error() . "\n"; }
public function actionSendPasswordEmail() { $worker = new GearmanWorker(); $worker->addServer(); $worker->addFunction("sendPasswordEmail", function (GearmanJob $job) { $workload = json_decode($job->workload(), true); $addresses = $workload['email']; $id = $workload['id']; $token = $workload['token']; Yii::log(json_encode(array('token' => $token)), 'info'); $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'union.zhantai.com'; $link = "http://{$host}/admin/login/setPassword/id/{$id}/token/{$token}"; $message = <<<EOT <p><b>亲爱的用户您好!</b></p> <p>这是一封铭智华通广告联盟密码设置邮件,<a target="_blank" href="{$link}">点击设置密码</a></p> <p>如果上述文字点击无效,请把下面网页地址复制到浏览器地址栏中打开:</p> <p><a target="_blank" href="{$link}">{$link}</a></p> EOT; $subject = '铭智广告联盟密码设置邮件'; return Yii::app()->mailer->send($addresses, $subject, $message); }); while ($worker->work()) { } }
/** * Starts a worker for the PECL library * * @param array $worker_list List of worker functions to add * @return void * */ protected function start_lib_worker($worker_list) { $thisWorker = new GearmanWorker(); $thisWorker->addOptions(GEARMAN_WORKER_NON_BLOCKING); $thisWorker->setTimeout(5000); foreach ($this->servers as $s) { $this->log("Adding server {$s}", GearmanManager::LOG_LEVEL_WORKER_INFO); $thisWorker->addServer($s); } foreach ($worker_list as $w) { $this->log("Adding job {$w}", GearmanManager::LOG_LEVEL_WORKER_INFO); $thisWorker->addFunction($w, array($this, "do_job"), $this); } $start = time(); while (!$this->stop_work) { if (@$thisWorker->work() || $thisWorker->returnCode() == GEARMAN_IO_WAIT || $thisWorker->returnCode() == GEARMAN_NO_JOBS) { if ($thisWorker->returnCode() == GEARMAN_SUCCESS) { continue; } if (!@$thisWorker->wait()) { if ($thisWorker->returnCode() == GEARMAN_NO_ACTIVE_FDS) { sleep(5); } } } /** * Check the running time of the current child. If it has * been too long, stop working. */ if ($this->max_run_time > 0 && time() - $start > $this->max_run_time) { $this->log("Been running too long, exiting", GearmanManager::LOG_LEVEL_WORKER_INFO); $this->stop_work = true; } } $thisWorker->unregisterAll(); }
public function action_index() { // Purge and terminate ob while (ob_get_level()) ob_end_flush(); # Create our worker object. $gearman_mworker= new GearmanWorker; # Add default server (localhost). $gearman_mworker->addServer(); # Register function "reverse" with the server. Change the worker function to # "reverse_fn_fast" for a faster worker with no output. $gearman_mworker->addFunction("make_request", array($this, "worker")); while($gearman_mworker->work()) { if ($gearman_mworker->returnCode() != GEARMAN_SUCCESS) { echo "return_code: " . $gearman_mworker->returnCode() . "\n"; break; } } }
<?php $base = preg_replace('|' . basename(dirname(__FILE__)) . '$|', '', dirname(__FILE__)); include_once $base . 'lib/config.php'; include_once $base . 'App.php'; $worker = new GearmanWorker(); $worker->addServer(); $worker->addFunction("change_theme", "change_theme"); while ($worker->work()) { } function change_theme($job) { $json = $job->workload(); $data = json_decode($json, true); $app = new App($data['token']); $app->themeWorker($data); } ?>
<?php date_default_timezone_set('Asia/Shanghai'); echo "starting\n"; $gmworker = new GearmanWorker(); $gmworker->addServer("10.0.128.219"); $gmworker->addFunction("hotblood_pack_task", "hotblood_pack_task_callback"); print "Waiting for job...\n"; while ($gmworker->work()) { if ($gmworker->returnCode() != GEARMAN_SUCCESS) { echo "return_code: " . $gmworker->returnCode() . "\n"; break; } } function hotblood_pack_task_callback($job) { echo "get tast at " . date("Y-m-d H:i:s", time()) . " " . $job->workload() . "\n"; popen("python ios_run.py " . $job->workload(), 'r'); return "task"; }
#!/usr/bin/env php <?php // Set time limit for run length $timeStarted = time(); $timeRunLimit = 1200; // Setup Gearman $worker = new GearmanWorker(); $worker->addServer('127.0.0.1'); $worker->addFunction("reverse", "reverse_fn"); while (1) { print "Waiting for job...\n"; $ret = $worker->work(); if ($worker->returnCode() != GEARMAN_SUCCESS) { break; } // Enforce run time limit if (time() - $timeStarted > $timeRunLimit) { exit; } } // Functions registered function reverse_fn($job) { $workload = $job->workload(); echo "Received job: " . $job->handle() . "\n"; echo "Workload: {$workload}\n"; $result = strrev($workload); for ($i = 1; $i <= 10; $i++) { $job->sendStatus($i, 10); sleep(1); }
/** * Read auto-loader */ include __DIR__ . '/config/loader.php'; /** * Read the configuration */ $config = (include __DIR__ . '/config/config.php'); /** * Read the services */ $di = new CliDi(); include __DIR__ . '/config/services.php'; /** * Create a console application */ $console = new ConsoleApp($di); $worker = new GearmanWorker(); $worker->setId(sha1(date("d.m.Y H:i:s"))); $worker->addServer('192.168.77.56', 4730); $worker->addFunction("send_metrix_calc", function ($job) use(&$console, &$di) { $di->set('workerJob', new MetrixResponse($di, $job, new FileAdapter(__DIR__ . "/logs/workjob_" . date("d-m-Y") . ".log"))); $arguments = json_decode($job->workload(), true); $console->setDi($di); $console->handle($arguments); }); while ($worker->work()) { if (GEARMAN_SUCCESS != $worker->returnCode()) { echo "Worker failed: " . $worker->error() . "\n"; } }
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Create our worker object. $worker = new GearmanWorker(); # Add default server (localhost). $worker->addServer('localhost', 4730); # Register function "reverse" with the server. $worker->addFunction("shell_execute", "shell_execute"); $options = getopt("P:"); $pid = getmypid(); file_put_contents($options['P'], $pid); while (1) { # print "Waiting for job...\n"; $ret = $worker->work(); if ($worker->returnCode() != GEARMAN_SUCCESS) { break; } } # A much simple reverse function function shell_execute($job) {
/** * @param string $ip * @param int $port */ public function addServer($ip, $port) { $this->logger->info("Adding Gearman server {$ip}:{$port}."); $this->gearman->addServer($ip, $port); }
$basedir = "/comic/bengou/"; $paths = array("115.28.51.131" => "/ts2/comic/bengou/"); $ips = get_network_interface(); foreach ($ips as $net) { if (array_key_exists($net["ip"], $paths)) { $basedir = $paths[$net["ip"]]; break; } } print_r("IP: {$ip}\n"); print_r("DIR: {$basedir}\n"); $failedCount = 0; $client = new GearmanClient(); $client->addServer("115.28.54.237", 4730); $worker = new GearmanWorker(); $worker->addServer('115.28.54.237', 4730); $worker->addFunction('comic-bengou', 'DownloadBengou'); // $worker->addFunction('comic-imanhua', 'DownloadImanhua'); while ($worker->work()) { } function DownloadBengou($job) { $args = $job->workload(); list($bookid, $chapterid) = explode(",", $args); //$bookid = "4182"; //$chapterid = 0005012703; return Action(CBenGou::$siteid, $bookid, intval($chapterid)); } function Action($siteid, $bookid, $chapterid) { global $basedir;
<?php $worker = new GearmanWorker(); $worker->addServer('127.0.0.1', 4730); $worker->addFunction('test1', 'test1'); $worker->addFunction('test2', 'test2'); // infinite loop while ($worker->work()) { } function test1() { } function test2() { }
#!/usr/bin/env php <?php require_once __DIR__ . '/config.php'; $worker = new GearmanWorker(); $worker->addServer(GEARMAN_SERVER_IP); $socket = null; $worker->addFunction('atoum', function (GearmanJob $job) { $workload = $job->workload(); echo 'Received job: ' . $job->handle() . PHP_EOL; echo 'Workload: ' . $workload . PHP_EOL; $pipes = array(); $proc = proc_open('vendor/bin/atoum -ft -d ' . 'tests/', array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")), $pipes, __DIR__ . '/../3284862/'); stream_set_blocking($pipes[1], 0); $read = array($pipes[1]); $write = array($pipes[1]); $expect = array($pipes[1]); $status = proc_get_status($proc); while ($status['running'] === true) { $result = stream_select($read, $write, $expect, 1); if ($result) { $cnt = stream_get_contents($pipes[1]); $job->sendData($cnt); writeSocket($cnt, GEARMAN_SERVER_IP, GEARMAN_SERVER_PORT); print $cnt; } $status = proc_get_status($proc); } return $status['exitcode'] ?: 0; }); while (true) { print 'Waiting for job...' . PHP_EOL;
/** * Adds into worker all defined Servers. * If any is defined, performs default method * * @param \GearmanWorker $gmworker Worker to perform configuration * @param array $servers Servers array * * @throws ServerConnectionException if a connection to a server was not possible. * * @return array Successfully added servers */ private function addServers(\GearmanWorker $gmworker, array $servers) { $successes = array(); if (!empty($servers)) { foreach ($servers as $server) { //We need to use try/catch here to handle case when the server is down try { //before addServer check if server is available if (TCPHelper::tryConnection($server['host'], $server['port'])) { if (@$gmworker->addServer($server['host'], $server['port'])) { $successes[] = $server; } } } catch (\GearmanException $e) { } } } else { if (@$gmworker->addServer()) { $successes[] = array('127.0.0.1', 4730); } } return $successes; }
/** * Adds into worker all defined Servers. * If any is defined, performs default method * * @param \GearmanWorker $gmworker Worker to perform configuration * @param array $servers Servers array * * @throws ServerConnectionException if a connection to a server was not possible. * * @return array Successfully added servers */ private function addServers(\GearmanWorker $gmworker, array $servers) { $successes = array(); if (!empty($servers)) { foreach ($servers as $server) { if (@$gmworker->addServer($server['host'], $server['port'])) { $successes[] = $server; } } } else { if (@$gmworker->addServer()) { $successes[] = array('127.0.0.1', 4730); } } return $successes; }
/** * Configuration application default DI * * @return FactoryDefault| CLI */ public function getDI() { if ($this->di) { return $this->di; } if ($this->appMode == 'cli') { $di = new FactoryDefault\CLI(); } else { $di = new FactoryDefault(); } //PHP5.3 not support $this in closure $self = $this; /********************************** * DI initialize for MVC core ***********************************/ //$di->set('application', $this); //call loadmodules will overwrite this $di->set('moduleManager', function () use($di) { $moduleManager = new ModuleManager(); $moduleManager->setEventsManager($di->getEventsManager()); return $moduleManager; }, true); //System global events manager $di->set('eventsManager', function () use($di) { $eventsManager = new EventsManager(); $eventsManager->enablePriorities(true); // dispatch caching event handler $eventsManager->attach("dispatch", new DispatchInterceptor(), -1); $eventsManager->enablePriorities(true); return $eventsManager; }, true); $di->set('config', function () use($self) { return $self->diConfig(); }, true); $di->set('router', function () use($self) { return $self->diRouter(); }, true); $di->set('dispatcher', function () use($di) { $dispatcher = new Dispatcher(); $dispatcher->setEventsManager($di->getEventsManager()); return $dispatcher; }, true); $di->set('modelsMetadata', function () use($self) { return $self->diModelsMetadata(); }, true); $di->set('modelsManager', function () use($di) { $config = $di->getConfig(); ModelManager::setDefaultPrefix($config->dbAdapter->prefix); //for solving db master/slave under static find method $modelsManager = new ModelManager(); return $modelsManager; }); $di->set('view', function () use($di) { $view = new View(); $view->setViewsDir(__DIR__ . '/views/'); $view->setEventsManager($di->getEventsManager()); return $view; }); $di->set('session', function () use($self) { return $self->diSession(); }); $di->set('tokenStorage', function () use($self) { return $self->diTokenStorage(); }, true); /********************************** * DI initialize for database ***********************************/ $di->set('dbMaster', function () use($self) { return $self->diDbMaster(); }, true); $di->set('dbSlave', function () use($self) { return $self->diDbSlave(); }, true); $di->set('transactions', function () use($di) { $transactions = new \Phalcon\Mvc\Model\Transaction\Manager(); $transactions->setDbService('dbMaster'); return $transactions; }, true); /********************************** * DI initialize for cache ***********************************/ $di->set('globalCache', function () use($self) { return $self->diGlobalCache(); }, true); $di->set('viewCache', function () use($self) { return $self->diViewCache(); }, true); $di->set('modelsCache', function () use($self) { return $self->diModelsCache(); }, true); $di->set('apiCache', function () use($self) { return $self->diApiCache(); }, true); $di->set('fastCache', function () use($self) { return $self->diFastCache(); }, true); /********************************** * DI initialize for queue ***********************************/ $di->set('queue', function () use($di) { $config = $di->getConfig(); $client = new \GearmanClient(); $client->setTimeout(1000); foreach ($config->queue->servers as $key => $server) { $client->addServer($server->host, $server->port); } return $client; }, true); $di->set('worker', function () use($di) { $config = $di->getConfig(); $worker = new \GearmanWorker(); foreach ($config->queue->servers as $key => $server) { $worker->addServer($server->host, $server->port); } return $worker; }, true); /********************************** * DI initialize for email ***********************************/ $di->set('mailer', function () use($self) { return $self->diMailer(); }, true); $di->set('mailMessage', 'Eva\\EvaEngine\\MailMessage'); $di->set('smsSender', function () use($self) { return $self->diSmsSender(); }, true); /********************************** * DI initialize for helpers ***********************************/ $di->set('url', function () use($di) { $config = $di->getConfig(); $url = new UrlResolver(); $url->setVersionFile($config->staticBaseUriVersionFile); $url->setBaseUri($config->baseUri); $url->setStaticBaseUri($config->staticBaseUri); return $url; }, true); $di->set('escaper', 'Phalcon\\Escaper'); $di->set('tag', function () use($di, $self) { Tag::setDi($di); $self->registerViewHelpers(); return new Tag(); }); $di->set('flash', 'Phalcon\\Flash\\Session'); $di->set('placeholder', 'Eva\\EvaEngine\\View\\Helper\\Placeholder'); $di->set('cookies', function () { $cookies = new \Phalcon\Http\Response\Cookies(); $cookies->useEncryption(false); return $cookies; }); $di->set('translate', function () use($self) { return $self->diTranslate(); }); $di->set('fileSystem', function () use($self) { return $self->diFileSystem(); }); $di->set('logException', function () use($di) { $config = $di->getConfig(); return new FileLogger($config->logger->path . 'error.log'); }); if ($this->appMode == 'cli') { $this->cliDI($di); } IoC::setDI($di); return $this->di = $di; }
<?php $worker = new GearmanWorker(); $worker->addServer("gearmand", "4730"); $worker->addFunction('getTemp', 'getTemp'); print "Waiting for a job...\n"; while ($worker->work()) { if ($worker->returnCode() !== GEARMAN_SUCCESS) { print 'Exiting with return code: ' . $gmworker->returnCode(); break; } } function getTemp($job) { $ch = curl_init(); $payload = json_decode($job->workload()); print "Getting current temperature for {$payload->city}...\n"; $city = urlencode($payload->city); curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => "http://api.openweathermap.org/data/2.5/weather?q={$city},us")); $result = json_decode(curl_exec($ch)); return round(($result->main->temp - 273.15) * 1.8 + 32); }
<?php require_once __DIR__ . '/../../../vendor/autoload.php'; use upload\model\inmuweb; ## Workers para syncronizar pagina web $w = new GearmanWorker(); $count = 0; $w->addServer(); ### estsblecer funciones disponibles $w->addFunction("delete", "delete"); //$w->addFunction("actContractLst","actContractLst",$c); while ($w->work()) { if ($w->returnCode() != GEARMAN_SUCCESS) { echo "return_code: " . $w->returnCode() . "\n"; break; } } function delete($job) { $inm = new inmuweb(); $data = json_decode($job->workload()); $result = $inm->delete($data->id); echo "Inmueble :" . $data->id . " -> {$result} \n"; return 0; }
<?php /** * This script demonstrates the unintuitive behavior of the Gearman * library when it comes to servicing jobs of different priorities. * * We'll use the same script as both the client and the worker for * convenience. */ // Create our worker $worker = new \GearmanWorker(); $worker->addServer('192.168.133.72', 4730); // Create our client $client = new \GearmanClient(); $client->addServer('192.168.133.72', 4730); // Service "foo" jobs by displaying "foo" $worker->addFunction('foo', function (\GearmanJob $job) { echo "foo\n"; }); // Service "bar" jobs by displaying "bar" $worker->addFunction('bar', function (\GearmanJob $job) { echo "bar\n"; }); // Add 25 LOW priority "foo" jobs to the queue. for ($i = 0; $i < 25; $i++) { $client->doLowBackground('foo', '{}'); } // Add 1 HIGH priority "bar" job to the queue. $client->doHighBackground('bar', '{}'); /** * Running ->work() will service the pending jobs.