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();
 }
 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;
         }
     }
 }
 /**
  * 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.º 4
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();
 }
 /**
  * Set up the GearmanWorker to run in non-blocking mode
  *
  * This allows you to do work "in between" jobs when its idle
  *
  * Events emitted:
  *  - Gearman.beforeWork: Called before GearmanWorker::work()
  *  - Gearman.afterWork: Called after GearmanWorker::work() actually processed a job
  *  - Gearman.beforeWait: Called before Gearman::wait() is called
  *  - Gearman.afterWait: Called after Gearman::wait() is called
  *
  * N.B: Gearman.beforeWork will be called even if there is no jobs to be processed,
  * it's meant as a simple wrapper around GearmanWorker::work() and GearmanWorker::wait()
  *
  * All events can abort the infinite loop by calling $event->stopPropagation();
  *
  * @return void
  */
 protected function _work()
 {
     $this->_worker->addOptions(GEARMAN_WORKER_NON_BLOCKING);
     // Infinite loop of doom until we die!
     while (true) {
         if (!$this->_triggerEvent('Gearman.beforeWork')) {
             break;
         }
         $this->_worker->work();
         if (!$this->_triggerEvent('Gearman.afterWork')) {
             break;
         }
         // If we processed a job, don't bother to wait
         if ($this->_worker->returnCode() == GEARMAN_SUCCESS) {
             continue;
         }
         if (!$this->_triggerEvent('Gearman.beforeWait')) {
             break;
         }
         $this->_worker->wait();
         if (!$this->_triggerEvent('Gearman.afterWait')) {
             break;
         }
     }
 }
Exemplo n.º 6
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.º 7
0
 public function work(\GearmanWorker $worker)
 {
     $worker->addOptions(GEARMAN_WORKER_NON_BLOCKING);
     $getWorkAttempts = 0;
     do {
         $workRes = $worker->work();
         $getWorkAttempts++;
         $this->logger->debug("Get work attempt res: " . serialize($workRes));
         $this->logger->debug("Attempts number: " . serialize($getWorkAttempts));
         sleep(1);
         if ($workRes) {
             $this->taskWasGot = true;
         }
     } while ($workRes === false && $getWorkAttempts < WorkersConstants::MAX_GET_TASK_ATTEMPTS);
     if ($worker->returnCode() != GEARMAN_SUCCESS) {
         $this->logger->error("Not correct Gearman worker execution:" . $worker->returnCode());
     }
     return null;
 }
Exemplo n.º 8
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;
 }
Exemplo n.º 9
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.º 10
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.º 11
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;
			}
		}
	}
 protected function work(\GearmanWorker $worker)
 {
     // @!?
     if (@$worker->work()) {
         return true;
     }
     switch ($worker->returnCode()) {
         case GEARMAN_SUCCESS:
         case GEARMAN_TIMEOUT:
             return true;
         case GEARMAN_IO_WAIT:
         case GEARMAN_NO_JOBS:
             return $this->wait($worker);
         default:
             break;
     }
     return false;
 }
Exemplo n.º 13
0
 /**
  * Given a GearmanWorker and an instance of Job, run it
  *
  * @param \GearmanWorker $gearmanWorker Gearman Worker
  * @param Object         $objInstance   Job instance
  * @param array          $jobs          Array of jobs to subscribe
  * @param integer        $iterations    Number of iterations
  * @param integer        $timeout       Timeout
  *
  * @return GearmanExecute self Object
  */
 private function runJob(\GearmanWorker $gearmanWorker, $objInstance, array $jobs, $iterations, $timeout = null)
 {
     /**
      * Set the output of this instance, this should allow workers to use the console output.
      */
     if ($objInstance instanceof GearmanOutputAwareInterface) {
         $objInstance->setOutput($this->output ?: new NullOutput());
     }
     /**
      * Every job defined in worker is added into GearmanWorker
      */
     foreach ($jobs as $job) {
         /**
          * worker needs to have it's context into separated memory space;
          * if it's passed as a value, then garbage collector remove the target
          * what causes a segfault
          */
         $this->workersBucket[$job['realCallableName']] = array('job_object_instance' => $objInstance, 'job_method' => $job['methodName'], 'jobs' => $jobs);
         $gearmanWorker->addFunction($job['realCallableName'], array($this, 'handleJob'));
     }
     /**
      * If iterations value is 0, is like worker will never die
      */
     $alive = 0 === $iterations;
     if ($timeout > 0) {
         $gearmanWorker->setTimeout($timeout * 1000);
     }
     /**
      * Executes GearmanWorker with all jobs defined
      */
     while (false === $this->stopWorkSignalReceived && $gearmanWorker->work()) {
         $iterations--;
         $event = new GearmanWorkExecutedEvent($jobs, $iterations, $gearmanWorker->returnCode());
         $this->eventDispatcher->dispatch(GearmanEvents::GEARMAN_WORK_EXECUTED, $event);
         if ($gearmanWorker->returnCode() != GEARMAN_SUCCESS) {
             break;
         }
         /**
          * Only finishes its execution if alive is false and iterations
          * arrives to 0
          */
         if (!$alive && $iterations <= 0) {
             break;
         }
     }
 }
Exemplo n.º 14
0
#!/usr/bin/env php
<?php 
namespace phinde;

chdir(dirname($argv[0]));
require_once __DIR__ . '/../src/init.php';
$gmworker = new \GearmanWorker();
$gmworker->addServer('127.0.0.1');
$gmworker->addFunction($GLOBALS['phinde']['queuePrefix'] . 'phinde_process', function (\GearmanJob $job) {
    $data = unserialize($job->workload());
    Log::info("-- Processing " . $data['url'] . ' (' . implode(',', $data['actions']) . ')');
    passthru('./process.php ' . escapeshellarg($data['url']) . ' ' . implode(' ', $data['actions']));
});
$gmworker->addFunction($GLOBALS['phinde']['queuePrefix'] . 'phinde_quit', function (\GearmanJob $job) {
    Log::info('Got exit job');
    $job->sendComplete('');
    exit(0);
});
while ($gmworker->work()) {
    if ($gmworker->returnCode() != GEARMAN_SUCCESS) {
        Log::error('Error running job: ' . $gmworker->returnCode());
        break;
    }
}
Exemplo n.º 15
0
 /**
  * Given a GearmanWorker and an instance of Job, run it
  *
  * @param \GearmanWorker $gearmanWorker Gearman Worker
  * @param Object         $objInstance   Job instance
  * @param array          $jobs          Array of jobs to subscribe
  * @param integer        $iterations    Number of iterations
  *
  * @return GearmanExecute self Object
  */
 private function runJob(\GearmanWorker $gearmanWorker, $objInstance, array $jobs, $iterations)
 {
     /**
      * Set the output of this instance, this should allow workers to use the console output.
      */
     if ($objInstance instanceof GearmanOutputAwareInterface) {
         $objInstance->setOutput($this->output ?: new NullOutput());
     }
     /**
      * Every job defined in worker is added into GearmanWorker
      */
     foreach ($jobs as $job) {
         $gearmanWorker->addFunction($job['realCallableName'], array($objInstance, $job['methodName']));
     }
     /**
      * If iterations value is 0, is like worker will never die
      */
     $alive = 0 == $iterations;
     /**
      * Executes GearmanWorker with all jobs defined
      */
     while ($gearmanWorker->work()) {
         $iterations--;
         $event = new GearmanWorkExecutedEvent($jobs, $iterations, $gearmanWorker->returnCode());
         $this->eventDispatcher->dispatch(GearmanEvents::GEARMAN_WORK_EXECUTED, $event);
         if ($gearmanWorker->returnCode() != GEARMAN_SUCCESS) {
             break;
         }
         /**
          * Only finishes its execution if alive is false and iterations
          * arrives to 0
          */
         if (!$alive && $iterations <= 0) {
             break;
         }
     }
 }
 *
 * Copyright (C) 2008 James M. Luedke (jluedke@jamesluedke.com)
 *                           Eric Day (eday@oddments.org)
 * All rights reserved.
 *
 * Use and distribution licensed under the PHP license.  See
 * the LICENSE file in this directory for full text.
 */
echo "Starting Thumbnail creator\n";
$gmw = new GearmanWorker();
$gmw->addServer();
# optional config paramsj
$args;
$gmw->addFunction("shrink_image", "resize_image", $args);
while ($gmw->work()) {
    switch ($gmw->returnCode()) {
        case GEARMAN_SUCCESS:
            break;
        default:
            echo "ERROR RET: " . $gmc->returnCode() . "\n";
            exit;
    }
}
echo "DONE\n";
/* simple function to resize an image
 * Requires the Imagick extension */
function resize_image($job, $args)
{
    $wrk = $job->workload();
    $data = unserialize($wrk);
    if (!$data['src'] || !$data['dest'] || !$data['x']) {
Exemplo n.º 17
0
    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;
    $ret = $worker->work();
    if ($worker->returnCode() != GEARMAN_SUCCESS) {
        print 'End of job (Status : ' . $worker->returnCode() . ')' . PHP_EOL;
        break;
    }
}
function getSocket($address, $port)
{
    $socket = socket_create(AF_INET, SOCK_STREAM, 0);
    if ($socket === FALSE) {
        throw new Exception("socket_create failed: reason: " . socket_strerror(socket_last_error()));
    }
    $result = socket_connect($socket, $address, $port);
    if ($result === false) {
        throw new Exception("socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($socket)));
    }
    return $socket;
Exemplo n.º 18
0
// Add the localhost:4730 as server (default)
$worker->addServer(); 

// Add the functions to the worker
// Fetch all photo Ids of this twitpic user
$worker->addFunction("fetchPhotoIds", "fetchPhotoIds");

// Fetch a photo from twitpic
$worker->addFunction("fetchPhoto", "fetchPhoto");

// This worker will destroy itself in 5 seconds.
$worker->setTimeout(5000);

// Keep worker alive as long as there are jobs
while (@$worker->work() || $worker->returnCode() == GEARMAN_IO_WAIT || 
		$worker->returnCode() == GEARMAN_NO_JOBS){
			
	if ($worker->returnCode() == GEARMAN_SUCCESS){
		echo date('d-m-Y H:i:s') . "| Job Successful \n";
		continue;
	}
	
	if (!@$worker->wait()) { 
		if ($worker->returnCode() == GEARMAN_NO_ACTIVE_FDS) { 
			// We are not connected to the Gearman Server
			// We shall not hammer the Gearman Server
			// We have patience, not much, but some.
			sleep(5); 

			continue; 
Exemplo n.º 19
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.º 20
0
$FENs = array();
$fp = fopen($pandaCave, 'rb', false);
$data = json_decode(fread($fp, 102400), true);
if (count($data) == 0) {
    echo "No servers found in FEN pool from Panda Cave.";
    exit;
}
foreach ($data as $server) {
    $gm->addServer($server['InternalIP']);
}
$args = null;
$stop = false;
global $stop;
$gm->addFunction("qarcGithubHook", "qarcGithubHook", $args);
echo "Added the function to gearman\n";
while (!$stop && ($gm->work() || $gm->returnCode() == GEARMAN_TIMEOUT)) {
    switch ($gm->returnCode()) {
        case GEARMAN_SUCCESS:
            echo "Gearman Success\n";
            break;
        case GEARMAN_TIMEOUT:
            echo "Gearman Timeout\n";
            break;
        default:
            echo "ERROR RET: " . $gmc->returnCode() . "\n";
            exit;
    }
}
echo "Quitting\n";
function qarcGithubHook($job, $args)
{
Exemplo n.º 21
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.º 22
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.º 23
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.º 24
0
#!/usr/local/momo_album/php/bin/php 
<?php 
error_reporting(E_ALL ^ E_NOTICE);
date_default_timezone_set("Asia/Shanghai");
define('SCRIPT_BASE', dirname(__FILE__) . DIRECTORY_SEPARATOR);
require SCRIPT_BASE . '../global.php';
$worker = new GearmanWorker();
$worker->addServers(Core::config('job_servers'));
$thumb = new Thumb();
$worker->addFunction("thumbnail", array($thumb, 'resize'));
$worker->addFunction("rotate", array($thumb, 'rotate'));
echo "Waiting for job...\n";
while ($worker->work()) {
    if ($worker->returnCode() != GEARMAN_SUCCESS) {
        echo "return_code: " . $worker->returnCode() . "\n";
        Core::debug('gmworkerlog', "return_code: " . $worker->returnCode());
        break;
    }
}
Exemplo n.º 25
0
set_include_path(implode(PATH_SEPARATOR, $paths));
//Autoloader
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$loader->registerNamespace('App_');
$loader->registerNamespace('Zend_');
$loader->setFallbackAutoloader(TRUE);
//Require the environment file
require ROOT_PATH . '/application/configs/environment.php';
//Start the worker
echo sprintf("%s: internal_upload worker ready and waiting for tasks...\n", date('r'));
$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction('internal_upload', 'internal_upload');
while ($worker->work()) {
    switch ($worker->returnCode()) {
        case GEARMAN_SUCCESS:
            break;
        default:
            echo sprintf("%s: Error ocurred: %s\n", date('r'), $worker->returnCode());
            exit;
    }
}
echo sprintf("%s: internal_upload worker finished\n");
/**
 * Functions registered with the worker
 *
 * @param object $job 
 * @return void
 */
function internal_upload($job)
Exemplo n.º 26
0
if (!array_key_exists('f', $options)) {
    help(1);
}
if (!array_key_exists('H', $options)) {
    $options['H'] = '127.0.0.1';
}
if (!array_key_exists('p', $options)) {
    $options['p'] = 4730;
}
$function = $options['f'];
$dir = $options['d'];
$host = $options['H'];
$port = $options['p'];
if (!array_key_exists('s', $options)) {
    $script = "{$function}.php";
} else {
    $script = $options['s'];
}
$file = "{$dir}/{$script}";
require $file;
$worker = new \GearmanWorker();
log("Gearman worker running... press Ctrl-c to stop");
$worker->addServer($host, $port);
$worker->addFunction($function, __NAMESPACE__ . '\\work');
log("Listening for function: {$function}");
while ($worker->work()) {
    if ($worker->returnCode() != GEARMAN_SUCCESS) {
        log("return_code: ", $worker->returnCode());
        break;
    }
}