Exemplo n.º 1
0
 /**
  * Constructor
  * Checks for the required gearman extension,
  * fetches the bootstrap and loads in the gearman worker
  *
  * @return Gearman_Worker
  */
 public function __construct($bootstrap)
 {
     if (!extension_loaded('gearman')) {
         throw new RuntimeException('The PECL::gearman extension is required.');
     }
     $this->_worker = $bootstrap->getWorker();
     if (empty($this->_registerFunction)) {
         throw new InvalidArgumentException(get_class($this) . ' must implement a registerFunction');
     }
     // allow for a small memory gap:
     $memoryLimit = ($this->_memory + 128) * 1024 * 1024;
     ini_set('memory_limit', $memoryLimit);
     $this->_worker->addFunction($this->_registerFunction, array(&$this, 'work'));
     $this->_worker->setTimeout($this->_timeout);
     $this->init();
     while ($this->_worker->work() || $this->_worker->returnCode() == GEARMAN_TIMEOUT) {
         if ($this->_worker->returnCode() == GEARMAN_TIMEOUT) {
             $this->timeout();
             continue;
         }
         if ($this->_worker->returnCode() != GEARMAN_SUCCESS) {
             $this->setError($this->_worker->returnCode() . ': ' . $this->_worker->getErrno() . ': ' . $this->_worker->error());
             break;
         }
     }
     $this->shutdown();
 }
Exemplo n.º 2
0
 public function work()
 {
     $this->_worker->addFunction($this->gearman_function(), array($this, 'do_job'));
     $this->_worker->work();
     // Killing after one job, so we don't run into unexpected behaviors or memory issues. Supervisord will respawn the php processes
     die;
 }
Exemplo n.º 3
0
 /**
  * Constructor
  * Checks for the required gearman extension,
  * fetches the bootstrap and loads in the gearman worker
  *
  * @param Zend_Application_Bootstrap_BootstrapAbstract $bootstrap
  * @return Zend_Gearman_Worker
  */
 public function __construct(Zend_Application_Bootstrap_BootstrapAbstract $bootstrap)
 {
     if (!extension_loaded('gearman')) {
         throw new RuntimeException('The PECL::gearman extension is required.');
     }
     $this->_bootstrap = $bootstrap;
     $this->_worker = $this->_bootstrap->bootstrap('gearmanworker')->getResource('gearmanworker');
     if (empty($this->_registerFunction)) {
         throw new InvalidArgumentException(get_class($this) . ' must implement a registerFunction');
     }
     // allow for a small memory gap:
     $memoryLimit = ($this->_memory + 128) * 1024 * 1024;
     ini_set('memory_limit', $memoryLimit);
     $this->_worker->addFunction($this->_registerFunction, array(&$this, 'work'));
     $this->_worker->setTimeout($this->_timeout);
     $this->init();
     $check = 10;
     $c = 0;
     while (@$this->_worker->work() || $this->_worker->returnCode() == GEARMAN_TIMEOUT) {
         $c++;
         if ($this->_worker->returnCode() == GEARMAN_TIMEOUT) {
             $this->timeout();
             continue;
         }
         if ($this->_worker->returnCode() != GEARMAN_SUCCESS) {
             $this->setError($this->_worker->returnCode() . ': ' . $this->_worker->getErrno() . ': ' . $this->_worker->error());
             break;
         }
         if ($c % $check === 0 && $this->isMemoryOverflow()) {
             break;
             // we've consumed our memory and the worker needs to be restarted
         }
     }
     $this->shutdown();
 }
Exemplo n.º 4
0
 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()) {
     }
 }
Exemplo n.º 5
0
 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;
 }
 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;
         }
     }
 }
Exemplo n.º 7
0
 public function actionIndex()
 {
     $w = new \GearmanWorker();
     $w->addServers($this->module->gman_server);
     $w->addFunction('kepco_file_download', function ($job) {
         $workload = Json::decode($job->workload());
         $bidid = $workload['bidid'];
         $attchd_lnk = $workload['attchd_lnk'];
         $this->stdout("한전파일> {$bidid} \n", Console::FG_GREEN);
         try {
             $saveDir = "/home/info21c/data/kepco/" . substr($bidid, 0, 4) . "/{$bidid}";
             @mkdir($saveDir, 0777, true);
             $cookie = $this->module->redis_get('kepco.cookie');
             $token = $this->module->redis_get('kepco.token');
             $downinfo = explode('|', $attchd_lnk);
             foreach ($downinfo as $info) {
                 $this->stdout(" > {$info}\n");
                 list($name, $url) = explode('#', $info);
                 $savePath = $saveDir . '/' . $name;
                 $cmd = "wget -q -T 30 --header 'Cookie: {$cookie}' --header \"X-CSRF-TOKEN: {$token}\"  --header 'Accept-Encoding: gzip' -O - '{$url}' | gunzip > \"{$savePath}\"";
                 //echo $cmd,PHP_EOL;
                 $res = exec($cmd);
             }
             $this->gman_fileconv->doBackground('fileconv', $bidid);
         } catch (\Exception $e) {
             $this->stdout("{$e}\n", Console::FG_RED);
             \Yii::error($e, 'kepco');
         }
         $this->stdout(sprintf("[%s] Peak memory usage: %s Mb\n", date('Y-m-d H:i:s'), memory_get_peak_usage(true) / 1024 / 1024), Console::FG_GREY);
         sleep(1);
     });
     while ($w->work()) {
     }
 }
Exemplo n.º 8
0
 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()) {
     }
 }
Exemplo n.º 9
0
 /**
  * @param string $function function name
  * @param callable $callback callable function function($data, \GearmanJob $job)
  * @return bool
  */
 public function register($function, callable $callback)
 {
     return $this->worker->addFunction($function, function (\GearmanJob $job) use($callback) {
         $result = Json::decode($job->workload());
         return $callback($result['data'], $job);
     });
 }
Exemplo n.º 10
0
 public function actionSuc()
 {
     $worker = new \GearmanWorker();
     $worker->addServers($this->module->gman_server);
     $worker->addFunction('ebidlh_suc_work', [SucWorker::className(), 'work']);
     while ($worker->work()) {
     }
 }
Exemplo n.º 11
0
 function listen()
 {
     foreach ($this->getConfiguration()->getFunctions() as $functionName => $callable) {
         $this->worker->addFunction($functionName, $this->wrap($callable, $functionName));
     }
     $this->suppressListen();
     $started = time();
     while ($this->worker->work()) {
         if ($this->worker->returnCode() != GEARMAN_SUCCESS) {
             $this->getLogger()->error('Gearman success fail with code:' . $this->worker->returnCode());
             $this->terminate(SIGTERM);
         }
         $this->suppressListen();
         $this->checkMatchedConditions();
         if (time() - $started < 1) {
             sleep(1);
         }
     }
 }
Exemplo n.º 12
0
 /**
  * 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];
 }
Exemplo n.º 13
0
 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();
     }
 }
Exemplo n.º 14
0
 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()) {
     }
 }
Exemplo n.º 15
0
 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);
     }
 }
 /**
  * Starts a worker for the PECL library
  *
  * @param   array   $worker_list    List of worker functions to add
  * @param   array   $timeouts       list of worker timeouts to pass to server
  * @return  void
  *
  */
 protected function start_lib_worker($worker_list, $timeouts = array())
 {
     $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);
         // see: https://bugs.php.net/bug.php?id=63041
         try {
             $thisWorker->addServers($s);
         } catch (\GearmanException $e) {
             if ($e->getMessage() !== 'Failed to set exception option') {
                 throw $e;
             }
         }
     }
     foreach ($worker_list as $w) {
         $timeout = isset($timeouts[$w]) ? $timeouts[$w] : null;
         $this->log("Adding job {$w} ; timeout: " . $timeout, GearmanManager::LOG_LEVEL_WORKER_INFO);
         $thisWorker->addFunction($w, array($this, "do_job"), $this, $timeout);
     }
     $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;
         }
         if (!empty($this->config["max_runs_per_worker"]) && $this->job_execution_count >= $this->config["max_runs_per_worker"]) {
             $this->log("Ran {$this->job_execution_count} jobs which is over the maximum({$this->config['max_runs_per_worker']}), exiting", GearmanManager::LOG_LEVEL_WORKER_INFO);
             $this->stop_work = true;
         }
     }
     $thisWorker->unregisterAll();
 }
Exemplo n.º 17
0
 public function run()
 {
     $w = new \GearmanWorker();
     $w->addServers($this->module->gman_server);
     $w->addFunction('kepco_work_suc2', function ($job) {
         try {
             $workload = Json::decode($job->workload());
             $this->stdout("%2%kkepco> [낙찰2] {$workload['id']} {$workload['no']} {$workload['name']}%n\n");
             $cookie = $this->module->redis_get('kepco.cookie');
             $token = $this->module->redis_get('kepco.token');
             $suc = new SucWorker2(['id' => $workload['id'], 'cookie' => $cookie, 'token' => $token]);
             $data = $suc->run();
             //print_r($data);
             $this->stdout(" > 공고번호 : {$data['notinum']}\n");
             $this->stdout(" > 예정가격 : {$data['yega']}\n");
             //$this->stdout(" > 복수예가 : {$data['multispare']}\n");
             $this->stdout(" > 1순위 : {$data['officenm1']}\n");
             $this->stdout(" > 참여수 : {$data['innum']}\n");
             $this->stdout(" > 진행상태 : {$data['bidproc']}\n");
             if (strlen($data['notinum']) < 10) {
                 return;
             }
             list($notino, $revno) = explode('-', $data['notinum']);
             if (preg_match('/^\\d{10}$/', $notino, $m)) {
                 $old_noti = substr($notino, 0, 4) . '-' . substr($notino, 4);
             } else {
                 $old_noti = substr($notino, 0, 3) . '-' . substr($notino, 3, 2) . '-' . substr($notino, 5);
             }
             $query = BidKey::find()->where(['whereis' => '03']);
             $query->andWhere("notinum like '{$old_noti}%' or notinum like '{$notino}%'");
             $bidkey = $query->orderBy('bidid desc')->limit(1)->one();
             if ($bidkey === null) {
                 return;
             }
             $data['bidid'] = $bidkey->bidid;
             $this->stdout(" > 개찰정보 저장 : {$bidkey->notinum} {$bidkey->constnm} ({$bidkey->state} {$bidkey->bidproc})\n");
             $this->module->gman_do('i2_auto_suc', Json::encode($data));
         } catch (\Exception $e) {
             $this->stdout("%r{$e}%n\n");
             \Yii::error($e, 'kepco');
         }
         $this->module->db->close();
         $this->memory_usage();
         sleep(1);
     });
     while ($w->work()) {
     }
 }
Exemplo n.º 18
0
 /**
  * Runs gearman worker for mkpur
  */
 public function actionIndex()
 {
     ini_set('memory_limit', '128M');
     echo '[database connection]', PHP_EOL;
     echo '  biddb  : ' . $this->module->biddb->dsn, PHP_EOL;
     echo '  infodb : ' . $this->module->infodb->dsn, PHP_EOL;
     echo '[gearman worker]', PHP_EOL;
     echo '  server   : ' . $this->module->gman_server, PHP_EOL;
     echo '  function : "mkpur_work"', PHP_EOL;
     echo 'start worker...', PHP_EOL;
     $worker = new \GearmanWorker();
     $worker->addServers($this->module->gman_server);
     $worker->addFunction('mkpur_work', [$this, 'mkpur_work']);
     while ($worker->work()) {
     }
 }
Exemplo n.º 19
0
 public function actionSuc()
 {
     $this->i2_gman_func = 'i2_auto_suc';
     $w = new \GearmanWorker();
     $w->addServers($this->module->gman_server);
     $w->addFunction('kepco_work_suc', function ($job) {
         try {
             $workload = Json::decode($job->workload());
             $this->stdout2("kepco> %g[worker]%n {$workload['no']} {$workload['revision']} {$workload['name']} %g{$workload['id']}%n\n");
             $cookie = $this->module->redis_get('kepco.cookie');
             $token = $this->module->redis_get('kepco.token');
             if (preg_match('/^\\d{10}$/', $workload['no'], $m)) {
                 $old_noti = substr($workload['no'], 0, 4) . '-' . substr($workload['no'], 4);
             } else {
                 $old_noti = substr($workload['no'], 0, 3) . '-' . substr($workload['no'], 3, 2) . '-' . substr($workload['no'], 5);
             }
             $notinum = $workload['no'] . '-' . $workload['revision'];
             $worker = new SucWorker(['id' => $workload['id'], 'cookie' => $cookie, 'token' => $token]);
             $data = $worker->run();
             $notinum = $data['notinum'] . '-' . $data['revision'];
             list($noti, $revision) = explode('-', $notinum);
             $bidkey = BidKey::find()->where("notinum like '{$noti}%' or notinum like '{$old_noti}%'")->andWhere(['whereis' => '03'])->orderBy('bidid desc')->limit(1)->one();
             if ($bidkey === null) {
                 return;
             }
             if ($data['bidproc'] === null) {
                 return;
             }
             $this->stdout2(" %yNEW%n\n");
             $data['notinum'] = $notinum;
             $data['constnm'] = $bidkey['constnm'];
             $data['bidid'] = $bidkey['bidid'];
             $this->stdout2("%g > do {$this->i2_gman_func} {$data['bidid']} {$data['bidproc']}%n\n");
             $this->module->gman_do($this->i2_gman_func, Json::encode($data));
         } catch (\Exception $e) {
             $this->stdout2("%r{$e}%n\n");
             \Yii::error($e, 'kepco');
         }
         $this->module->db->close();
         $this->stdout2(sprintf("[%s] Peak memory usage: %sMb\n", date('Y-m-d H:i:s'), memory_get_peak_usage(true) / 1024 / 1024), Console::FG_GREY);
         sleep(1);
     });
     while ($w->work()) {
     }
 }
Exemplo n.º 20
0
 /**
  * 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->addServers($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;
         }
         if (!empty($this->config["max_runs_per_worker"]) && $this->job_execution_count >= $this->config["max_runs_per_worker"]) {
             $this->log("Ran {$this->job_execution_count} jobs which is over the maximum({$this->config['max_runs_per_worker']}), exiting", GearmanManager::LOG_LEVEL_WORKER_INFO);
             $this->stop_work = true;
         }
     }
     $thisWorker->unregisterAll();
 }
Exemplo n.º 21
0
 /**
  * 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";
 }
Exemplo n.º 22
0
	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;
			}
		}
	}
Exemplo n.º 23
0
    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()) {
        }
    }
Exemplo n.º 24
0
<?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;
}
Exemplo n.º 25
0
<?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);
}
Exemplo n.º 26
0
<?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";
}
Exemplo n.º 27
0
<?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);
}
?>
 
Exemplo n.º 28
0
<?php

require_once "Converter.php";
$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction("convert", array(Converter::defaultConverter(), 'doConvert'));
$logger = new Logger();
while (1) {
    $logger->waitingForJob();
    $ret = $worker->work();
    // work() will block execution until a job is delivered
    if ($worker->returnCode() != GEARMAN_SUCCESS) {
        break;
    }
}
Exemplo n.º 29
0
/**
 * 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";
    }
}
Exemplo n.º 30
0
<?php

$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction('say', function (GearmanJob $job) {
    $workload = $job->workload();
    //接收client传递的数据
    echo 'process id: ' . getmypid() . '; receive data:' . $workload . PHP_EOL;
    return strrev($workload);
    //仅作反转处理
});
//无际循环运行,gearman内部已有处理,不会出现占用过高死掉的情况
while ($worker->work()) {
    if ($worker->returnCode() !== GEARMAN_SUCCESS) {
        echo 'error' . PHP_EOL;
    }
}