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'); } }
/** * 获取gearmant客户端 * @return \GearmanClient */ private function getClient() { if ($this->client !== null) { return $this->client; } $client = new \GearmanClient(); $conStrings = array(); foreach ($this->servers as $ser) { if (is_string($ser)) { $conStrings[] = $ser; } else { $conStrings[] = $ser['host'] . (isset($ser['port']) ? ':' . $ser['port'] : ''); } } $conString = false; if (count($conStrings) > 0) { $conString = implode(',', $conStrings); } if ($conString) { $result = $client->addServers($conString); if ($result) { $this->echoTraceLog('服务器添加成功! servers: ' . $conString); } else { $this->echoErrorLog('服务器添加失败! servers: ' . $conString); return false; } } $this->client = $client; return $this->client; }
public function init() { $this->client = new \GearmanClient(); $this->worker = new \GearmanWorker(); if (empty($this->servers)) { $this->servers = ['127.0.0.1:4730']; } $this->client->addServers(implode(',', $this->servers)); $this->worker->addServers(implode(',', $this->servers)); if (!empty($this->clientOptions)) { $this->client->setOptions(implode(' | ', $this->clientOptions)); } if (!empty($this->workerOptions)) { $this->worker->setOptions(implode(' | ', $this->workerOptions)); } }
public function __construct(\GearmanClient $client = null) { if (is_null($client)) { $client = new \GearmanClient(); $client->addServers("localhost:4730"); } $this->client = $client; }
/** * This method will instantiate the object, configure it and return it * * @return Zend_Cache_Manager */ public static function getInstance() { $config = App_DI_Container::get('ConfigObject'); $gearmanClient = new GearmanClient(); if (!empty($config->gearman->servers)) { $gearmanClient->addServers($config->gearman->servers->toArray()); } else { $gearmanClient->addServer(); } return $gearmanClient; }
/** * do driver instance init */ public function setup() { $settings = $this->getSettings(); if (empty($settings)) { throw new BoxRouteInstanceException('init driver instance failed: empty settings'); } $curInst = new \GearmanClient(); $curInst->addServers($settings['gearmanHosts']); $this->instance = $curInst; $this->isAvailable = $this->instance ? true : false; }
public function run($task) { $client = new GearmanClient(); $client->addServers($task["server"]); $client->doBackground($task["cmd"], $task["ext"]); if (($code = $client->returnCode()) != GEARMAN_SUCCESS) { Main::log_write("Gearman:" . $task["cmd"] . " to " . $task["server"] . " error,code=" . $code); exit; } Main::log_write("Gearman:" . $task["cmd"] . " to " . $task["server"] . " success,code=" . $code); exit; }
/** * 获取客户端连接 * @return bool|\GearmanClient */ private function getClient() { if ($this->client != null) { return $this->client; } $client = new \GearmanClient(); $conString = $this->conString; $result = $client->addServers($conString); if (!$result) { $this->logError('服务器添加失败! servers: ' . $conString); return false; } $this->client = $client; return $this->client; }
/** * Functions registered with the worker * * @param GearmanJob $job * @return boolean */ function send_email($job) { //Get the info of the job $workload = unserialize($job->workload()); //Ensure the minimum info if (!array_key_exists('text', $workload) && !array_key_exists('html', $workload)) { echo sprintf("%s: To send an email we need at least the text or html\n", date('r')); $job->sendFail(); return FALSE; } if (!array_key_exists('to', $workload) || array_key_exists('to', $workload) && empty($workload['to'])) { echo sprintf("%s: To send an email we need the recipient address\n", date('r')); $job->sendFail(); return FALSE; } if (!array_key_exists('subject', $workload)) { echo sprintf("%s: To send an email we need the subject of the email\n", date('r')); $job->sendFail(); return FALSE; } echo sprintf("%s: Received a task to send email to %s\n", date('r'), implode(', ', is_array($workload['to']) ? $workload['to'] : array($workload['to']))); $config = getConfig(); $mail = new Zend_Mail('utf-8'); if ($config->system->email_system->send_by_amazon_ses) { $transport = new App_Mail_Transport_AmazonSES(array('accessKey' => $config->amazon->aws_access_key, 'privateKey' => $config->amazon->aws_private_key)); } if (array_key_exists('text', $workload)) { $mail->setBodyText($workload['text']); } if (array_key_exists('html', $workload)) { $mail->setBodyHtml($workload['html']); } if (array_key_exists('reply', $workload) && !empty($workload['reply'])) { $mail->setReplyTo($workload['reply']); } $mail->setFrom($config->amazon->ses->from_address, $config->amazon->ses->from_name); $mail->addTo($workload['to']); $mail->setSubject($workload['subject']); //Prepare gearman client $config = getConfig(); $gearmanClient = new GearmanClient(); if (!empty($config->gearman->servers)) { $gearmanClient->addServers($config->gearman->servers->toArray()); } else { $gearmanClient->addServer(); } //Add the callbacks $gearmanClient->setCompleteCallback('taskCompleted'); $gearmanClient->setFailCallback('taskFailed'); try { if (isset($transport) && $transport instanceof App_Mail_Transport_AmazonSES) { $mail->send($transport); } else { $mail->send(); } //Some status info echo sprintf("%s: Email (%s) sent to %s\n", date('r'), $workload['subject'], implode(', ', is_array($workload['to']) ? $workload['to'] : array($workload['to']))); echo sprintf("%s: Task finished successfully\n\n", date('r')); $job->sendComplete(TRUE); return TRUE; } catch (Exception $e) { logError(sprintf("Error while sending an email to %s.\n\nError: %s\n", $workload['to'], $e->getMessage())); $job->sendFail(); return FALSE; } }
public static function work($job) { $workload = $job->workload(); echo $workload, PHP_EOL; $workload = Json::decode($workload); $module = \ebidlh\Module::getInstance(); $pub = \Yii::createObject(['class' => \ebidlh\Redis::className(), 'hostname' => $module->redis_server]); $sub = \Yii::createObject(['class' => \ebidlh\Redis::className(), 'hostname' => $module->redis_server]); $channel = \Yii::$app->security->generateRandomString(); try { if (ArrayHelper::keyExists('bidproc', $workload)) { switch ($workload['bidproc']) { case '취소공고': $bidproc = 'C'; break; //case '연기공고': $bidproc='L'; break; //case '연기공고': $bidproc='L'; break; default: $bidproc = 'B'; } $bidkey = BidKey::findOne(['whereis' => '05', 'notinum' => $workload['notinum'] . '-' . $workload['subno'], 'bidproc' => $bidproc]); if ($bidkey !== null) { throw new PassException(); } } switch ($workload['bidtype']) { case '공사': $url = self::URL_CON; break; case '용역': $url = self::URL_SER; break; case '물품': $url = self::URL_PUR; break; case '지급자재': $url = self::URL_PUR2; break; default: throw new \Exception('invalid bidtype'); } $pub->publish('ebidlh-bid', ['cmd' => 'open-work', 'channel' => $channel]); $sub->subscribe([$channel], function ($redis, $chan, $msg) use($pub, $channel, $workload, $url) { if ($msg === 'ready') { $pub->publish($channel . '-client', ['url' => $url, 'post' => http_build_query(['bidNum' => $workload['notinum'], 'bidDegree' => $workload['subno'], 'cstrtnJobGbCd' => $workload['param3'], 'emrgncyOrder' => $workload['param4']])]); return; } $html = iconv('euckr', 'utf-8//IGNORE', $msg); $html = strip_tags($html, '<th><tr><td><a>'); $html = preg_replace('/<th[^>]*>/i', '<th>', $html); if (strpos($html, '한국정보인증(주)의 보안S/W를 설치중입니다') > 0) { return; } $html = preg_replace('/<tr[^>]*>/i', '<tr>', $html); $html = preg_replace('/<td[^>]*>/i', '<td>', $html); $data = []; $files = []; $p = '#<tr>' . ' <td>(?<ftype>[^<]*)</td>' . ' <td><a.*fn_dds_open\\(\'\\d+\',\'(?<rname>[^\']*)\',[^>]*>(?<fname>[^<]*)</a></td>' . ' </tr>#i'; $p = str_replace(' ', '\\s*', $p); if (preg_match_all($p, $html, $matches, PREG_SET_ORDER)) { foreach ($matches as $m) { $fname = trim($m['fname']); $rname = trim($m['rname']); $files[] = "{$fname}#('bidinfo','{$fname}','{$rname}')"; } } $data['attchd_lnk'] = implode('|', $files); $html = strip_tags($html, '<th><tr><td>'); //공고종류 $p = '#공고종류</th> <td>(?<bidproc>[^<]*)</td>#i'; $data['bidproc'] = self::match($p, $html, 'bidproc'); //공고명 $p = '#입찰공고건명</th> <td>(?<constnm>.+)본 공고는 지문인식#i'; $data['constnm'] = self::match($p, $html, 'constnm'); //공고부서 $p = '#공고부서</th> <td>(?<org>[^<]*)</td>#i'; $data['org'] = self::match($p, $html, 'org'); //추정가격 $p = '#추정가격</th> <td>(?<presum>\\d+(,\\d{1,3})*)원#i'; $data['presum'] = self::match($p, $html, 'presum'); //기초금액 $p = '#기초금액</th> <td>(?<basic>\\d+(,\\d{1,3})*)원#i'; $data['basic'] = self::match($p, $html, 'basic'); //계약방법 $p = '#계약방법</th> <td>(?<contract>[^<]*)</td>#i'; $data['contract'] = self::match($p, $html, 'contract'); //입찰방식 $p = '#입찰방식</th> <td>(?<bidcls>[^<]*)</td>#i'; $data['bidcls'] = self::match($p, $html, 'bidcls'); //낙찰자선정방법 $p = '#낙찰자선정방법</th> <td>(?<succls>[^<]*)</td>#i'; $data['succls'] = self::match($p, $html, 'succls'); //공동수급협정서접수마감일시 $p = '#공동수급협정서접수마감일시</th> <td>(?<hyupenddt>[^<]*)</td>#i'; $data['hyupenddt'] = self::match($p, $html, 'hyupenddt'); //입찰서접수개시일시 $p = '#입찰서접수개시일시</th> <td>(?<opendt>[^<]*)</td>#i'; $data['opendt'] = self::match($p, $html, 'opendt'); //입찰서접수마감일시 $p = '#입찰서접수마감일시</th> <td>(?<closedt>[^<]*)</td>#i'; $data['closedt'] = self::match($p, $html, 'closedt'); //입찰참가신청서접수마감일시 $p = '#입찰참가신청서접수마감일시</th> <td>(?<registdt>[^<]*)</td>#i'; $data['registdt'] = self::match($p, $html, 'registdt'); //개찰일시 $p = '#개찰일시</th> <td>(?<constdt>[^<]*)</td>#i'; $data['constdt'] = self::match($p, $html, 'constdt'); //현장설명일시 $p = '#현장설명일시</th> <td>(?<explaindt>[^<]*)</td>#i'; $data['explaindt'] = self::match($p, $html, 'explaindt'); //공고변경사유 $p = '#공고변경사유</th> <td>(?<bidcomment_mod>[^<]*)</td>#i'; $data['bidcomment_bid'] = self::match($p, $html, 'bidcomment_mod'); //투찰제한 $p = '#투찰제한정보 <tr>' . ' <th>참가지역1</th> <td>(?<local1>[^<]*)</td>' . ' <th>참가지역2</th> <td>(?<local2>[^<]*)</td>' . ' <th>참가지역3</th> <td>(?<local3>[^<]*)</td>' . ' <th>참가지역4</th> <td>(?<local4>[^<]*)</td>' . ' </tr>#i'; $p = str_replace(' ', '\\s*', $p); if (preg_match($p, $html, $m)) { $data['local1'] = trim($m['local1']); $data['local2'] = trim($m['local2']); $data['local3'] = trim($m['local3']); $data['local4'] = trim($m['local4']); } //지역의무공동업체제한 $p = '#지역의무공동업체제한 <tr>' . ' <th>참가지역1</th> <td>(?<local1>[^<]*)</td>' . ' <th>참가지역2</th> <td>(?<local2>[^<]*)</td>' . ' <th>참가지역3</th> <td>(?<local3>[^<]*)</td>' . ' <th>참가지역4</th> <td>(?<local4>[^<]*)</td>' . ' </tr>#i'; $p = str_replace(' ', '\\s*', $p); if (preg_match($p, $html, $m)) { $data['contloc1'] = trim($m['local1']); $data['contloc2'] = trim($m['local2']); $data['contloc3'] = trim($m['local3']); $data['contloc4'] = trim($m['local4']); } print_r($data); if (strpos($data['bidproc'], '취소공고') !== false) { $bidproc = 'C'; } else { $bidproc = 'B'; } $bidkey = BidKey::findOne(['whereis' => '05', 'notinum' => $workload['notinum'] . '-' . $workload['subno'], 'bidproc' => $bidproc]); if ($bidkey === null) { if (strpos($data['bidproc'], '취소공고') !== false) { $bidproc = 'C'; } } $pub->publish($channel . '-client', ['url' => 'close', 'post' => '']); $redis->close(); return; }); } catch (PassException $e) { } catch (\RedisException $e) { $sub->close(); echo Console::renderColoredString('%r' . $e->getMessage() . '%n'), PHP_EOL; $gman_client = new \GearmanClient(); $gman_client->addServers($module->gman_server); $gman_client->doBackground('ebidlh_bid_work', $job->workload()); } catch (\Exception $e) { $sub->close(); echo Console::renderColoredString("%r{$e}%n"), PHP_EOL; \Yii::error($job->workload() . "\n" . $e, 'ebidlh'); } $module->db->close(); echo Console::renderColoredString("%c" . sprintf("[%s] Peak memory usage: %sMb", date('Y-m-d H:i:s'), memory_get_peak_usage(true) / 1024 / 1024) . "%n"), PHP_EOL; }
public function init() { parent::init(); $gman_client = new \GearmanClient(); $gman_client->addServers('115.168.48.242'); }
protected function __property_client() { $return = new \GearmanClient(); $return->addServers($this->server); return $return; }
/** * * @return \GearmanClient */ public function client() { $gmClient = new \GearmanClient(); $gmClient->addServers(GEARMAN_SERVERS); return $gmClient; }
/** * @return \GearmanClient * @throws MQException */ protected function client() { $client = new \GearmanClient(); $client->addServers($this->dns); if (($haveGoodServer = $client->ping($this->id)) === false) { throw new MQException("Server does not access: {$this->dns}"); } return $client; }
public function sendMessage($msg) { $gman = new \GearmanClient(); $gman->addServers('115.68.48.242'); $gman->doBackground('send_chat_message_from_admin', Json::encode(['recv_id' => 149, 'message' => $msg])); }
<?php define('CELLIO', true); define('LIBPATH', realpath(dirname(__FILE__) . '/..') . '/lib'); require_once LIBPATH . '/init.php'; // Variables, assemble! $time = gmdate('r'); $req = array_change_key_case($_REQUEST, CASE_UPPER); $recipientSID = $req['ACCOUNTSID']; $callnum_recv = $req['TO']; $callnum_from = $req['FROM']; $geo = gen_geo_output($req, 'pre'); $email_to = $config['ACCOUNTS'][$recipientSID]['EMAIL']; $email_subject = 'Twilio Call From ' . $callnum_from; $email_body = "Call received to {$callnum_recv}\n\nTime: {$time}\n\nFrom: {$callnum_from}{$geo}"; // Use either Gearman or non-asynchronous fallback if ($config['OPTS']['USE_GEARMAN']) { $gmc = new GearmanClient(); $gmc->addServers($config['OPTS']['GEARMAN_SERVERS']); $res = $gmc->doBackground('send_email', json_encode(array('TO' => $email_to, 'SUBJECT' => $email_subject, 'BODY' => $email_body))); } else { send_email($email_to, $config['OPTS']['EMAIL_FROM'], $email_subject, $email_body); } // Craft voicemail request $twiml = array(array('name' => 'Say', 'value' => $config['ACCOUNTS'][$recipientSID]['VOICEMAIL_PROMPT']), array('name' => 'Record', 'attributes' => array('action' => $config['OPTS']['URL'] . '/voicemail.php', 'timeout' => $config['OPTS']['VOICEMAIL_TIMEOUT'], 'maxLength' => $config['OPTS']['VOICEMAIL_LEN'], 'trim' => $config['OPTS']['VOICEMAIL_TRIM'], 'playBeep' => $config['OPTS']['VOICEMAIL_BEEP'])), array('name' => 'Say', 'value' => $config['OPTS']['VOICEMAIL_TIMEOUT_MSG'])); // Tell Twilio to capture a voicemail print_TwiML($twiml);
static function createTasks($servers = null) { $client = new \GearmanClient(); $client->addServers($servers); return new Tasks($client); }
public static function work($job) { $workload = $job->workload(); $workload = Json::decode($workload); $module = \ebidlh\Module::getInstance(); $pub = \Yii::createObject(['class' => \ebidlh\Redis::className(), 'hostname' => $module->redis_server]); $sub = \Yii::createObject(['class' => \ebidlh\Redis::className(), 'hostname' => $module->redis_server]); $channel = \Yii::$app->security->generateRandomString(); try { $bidkey = BidKey::findOne(['whereis' => '05', 'notinum' => $workload['notinum'] . '-' . $workload['subno']]); if ($bidkey === null) { throw new \Exception('개찰: 입찰공고 미등록 공고입니다. (' . $workload['notinum'] . ')'); } static::print_bid($bidkey); if (ArrayHelper::keyExists('status', $workload) && $workload['status'] === '유찰') { if ($bidkey->bidproc === 'F' and !ArrayHelper::keyExists('force', $workload)) { throw new PassException(); } //todo throw new PassException(); } if ($bidkey->bidproc === 'S' and !ArrayHelper::keyExists('force', $workload)) { throw new PassException(); } $pub->publish('ebidlh-suc', ['cmd' => 'open-work', 'channel' => $channel]); $sub->subscribe([$channel], function ($redis, $chan, $msg) use($pub, $channel, $workload, $bidkey) { if ($msg === 'ready') { $pub->publish($channel . '-client', ['url' => self::URL, 'post' => http_build_query(['bidNum' => $workload['notinum'], 'bidDegree' => $workload['subno']])]); return; } $html = iconv('euckr', 'utf-8//IGNORE', $msg); $html = strip_tags($html, '<th><tr><td>'); $html = preg_replace('/<th[^>]*>/i', '<th>', $html); if (strpos($html, '한국정보인증(주)의 보안S/W를 설치중입니다') > 0) { return; } $p = '@<td[^>]+>(?<no>\\d{1,2})</td>' . ' <td(?<selms>[^>]+)>(?<mprice>\\d+(,\\d{1,3})*) </td>' . ' <td[^>]+>(?<mcnt>\\d*)</td>@i'; $p = str_replace(' ', '\\s*', $p); $multispares = []; $selms = []; $mulcnts = []; if (preg_match_all($p, $html, $matches, PREG_SET_ORDER)) { foreach ($matches as $m) { $multispares[$m['no'] - 1] = str_replace(',', '', $m['mprice']); if (strpos($m['selms'], 'COLOR: #ff0000;') > 0) { $selms[] = $m['no']; } $mulcnts[$m['no'] - 1] = $m['mcnt']; } } ksort($multispares); ksort($mulcnts); sort($selms); $html = preg_replace('/<td[^>]*>/i', '<td>', $html); $yega = ''; $p = '#<th> 예정가격 </th> <td>(?<yega>\\d+(,\\d{3})*) 원</td>#i'; $p = str_replace(' ', '\\s*', $p); if (preg_match($p, $html, $m)) { $yega = str_replace(',', '', $m['yega']); } //참여업체 (금액으로 sort됨) $succoms = []; $succoms_plus = []; $succoms_minus = []; $p = '#<tr>' . ' <td>(?<seq>\\d+)</td>' . ' <td>(?<officeno>[^>]*)</td>' . ' <td>(?<officenm>[^>]*)</td>' . ' <td>(?<success>\\d+(,\\d{1,3})*)</td>' . ' <td>(?<pct>[^<]*)</td>' . ' <td>(?<selms>[^<]*)</td>' . ' <td>(?<etc>[^<]*)</td>' . ' </tr>#i'; $p = str_replace(' ', '\\s*', $p); if (preg_match_all($p, $html, $matches, PREG_SET_ORDER)) { foreach ($matches as $m) { $succom = ['seq' => $m['seq'], 'officeno' => str_replace('-', '', trim($m['officeno'])), 'officenm' => trim($m['officenm']), 'success' => str_replace(',', '', trim($m['success'])), 'pct' => trim($m['pct']), 'selms' => trim($m['selms']), 'etc' => trim($m['etc'])]; $succoms[$succom['seq']] = $succom; switch ($succom['etc']) { case '점수미달': case '낙찰하한율미만': case '부적격': $succoms_minus[] = $succom['seq']; break; default: $succoms_plus[] = $succom['seq']; } } } $i = 1; foreach ($succoms_plus as $seq) { $succoms[$seq]['rank'] = $i; $i++; } $i = count($succoms_minus) * -1; foreach ($succoms_minus as $seq) { $succoms[$seq]['rank'] = $i; $i++; } $innum = count($succoms); Console::startProgress(0, $innum); $n = 1; foreach ($succoms as $com) { Console::updateProgress($n, $innum); $n++; } Console::endProgress(); $pub->publish($channel . '-client', ['url' => 'close', 'post' => '']); $redis->close(); return; }); } catch (PassException $e) { } catch (\RedisException $e) { $sub->close(); echo Console::renderColoredString('%rRedisException: ' . $e->getMessage() . '%n'), PHP_EOL; $gman_client = new \GearmanClient(); $gman_client->addServers($module->gman_server); $gman_client->doBackground('ebidlh_suc_work', $job->workload()); } catch (\Exception $e) { $sub->close(); echo Console::renderColoredString("%r{$e}%n"), PHP_EOL; \Yii::error($job->workload() . "\n" . $e, 'ebidlh'); } echo Console::renderColoredString("%c" . sprintf("[%s] Peak memory usage: %sMb", date('Y-m-d H:i:s'), memory_get_peak_usage(true) / 1024 / 1024) . "%n"), PHP_EOL; }
/** * Configures internal client reference to use the list of specified servers. * This list is specified using the configure class. * * @return void **/ protected static function _setServers() { $servers = Configure::read('Gearman.servers') ?: array('127.0.0.1:4730'); static::$_client->addServers(implode(',', $servers)); }
/** * * 图片旋转接口 * GET rotate/:id.json?direction={方向}&size={尺寸} */ public function rotate($pid) { $direction = intval($_GET['direction']); $size = intval($_GET['size']); $size = in_array($size, Core::config('photo_standard_type')) ? $size : 130; if ($direction != -1) { $direction = 1; } if (!$pid) { $this->response(ResponseType::ERROR_LACKPARAMS); } $client = new GearmanClient(); $client->addServers(Core::config('job_servers')); $client->setTimeout(3000); $result = @$client->doHigh("rotate", serialize(array($pid, $direction))); $result && ($sid = @unserialize($result)); if (!$sid) { $thumb = new Thumb(); if ($thumb->rotate(NULL, $pid, $direction)) { $sid = TRUE; } } if ($sid) { $photoModel = new Models\Photo(); $imgurls = $photoModel->geturi($pid, $size); $return['src'] = $imgurls[0]; $this->response(ResponseType::PHOTO_ROTATE_OK, '', $return); } else { $this->response(ResponseType::PHOTO_ROTATE_ERROR); } }