/**
  * Method to run a domain job whose workload is a serialized JobRequestInterface
  *
  * @param \GearmanJob $job Object with job parameters
  *
  * @throws \Ice\Domain\Jobs\UnsupportedJobException
  * @throws \Exception re-throw uncaught exceptions
  * @return boolean
  *
  * @Gearman\Job(
  *     iterations = 1,
  *     name = "addDomainJob",
  *     description = "Data should be an json-encoded object containing at least a 'name' property. That domain job wll be executed"
  * )
  */
 public function addDomainJob($job)
 {
     $jobRequest = $this->requestSerializer->deserializeJobRequest($job->workload());
     if ($this->logger) {
         $this->logger->notice("Job received", [$job->workload()]);
     }
     if (!$this->director->hasWorkerProviderFor($jobRequest->getName())) {
         if ($this->logger) {
             $this->logger->critical("No worker available for job of name: " . $jobRequest->getName(), [$job->workload()]);
         }
         throw new UnsupportedJobException("No worker available for job of name: " . $jobRequest->getName());
     }
     $worker = $this->director->getWorkerProviderFor($jobRequest->getName())->getWorkerFor($jobRequest->getName());
     try {
         if ($this->eventDispatcher) {
             $this->eventDispatcher->dispatch('ice.job.pre_execute');
         }
         $worker->execute($jobRequest);
         if ($this->logger) {
             $this->logger->notice("Job complete", [$job->workload()]);
         }
     } catch (\Exception $e) {
         if ($this->logger) {
             $this->logger->critical("Uncaught exception when processing job", array('workload' => $job->workload(), 'message' => $e->getMessage(), 'stack_trace' => $e->getTrace(), 'exception' => $e));
         }
         //Re-throw the exception anyway, so that gearman knows the job has failed.
         throw $e;
     }
     return true;
 }
Beispiel #2
0
 protected function processQuery(\GearmanJob $job, Query $query)
 {
     $start = microtime(true);
     $job->sendStatus(0, 100);
     $tempfile = tempnam(sys_get_temp_dir(), 'transmute_image');
     $tempdest = tempnam(sys_get_temp_dir(), 'transmute_image');
     if (false === ($filecontent = @file_get_contents($query->getFile()))) {
         $this->logger->addInfo(sprintf('Unable to download file `%s`', $query->getFile()));
         return new Result($job->handle(), $query->getUuid(), $job->workload(), null, $this->workerName, $start, microtime(true), array(), array(sprintf('Unable to download file `%s`', $query->getFile())));
     }
     $this->logger->addInfo(sprintf('file %s retrieved', $query->getFile()));
     $job->sendStatus(30, 100);
     file_put_contents($tempfile, $filecontent);
     unset($filecontent);
     $job->sendStatus(50, 100);
     $specification = new Image();
     $width = $height = null;
     foreach ($query->getParameters() as $name => $value) {
         switch ($name) {
             case 'width':
                 $width = $value;
                 break;
             case 'height':
                 $height = $value;
                 break;
             case 'quality':
                 $specification->setQuality($value);
                 break;
         }
     }
     if (null !== $width && null !== $height) {
         $specification->setDimensions($width, $height);
     }
     try {
         $this->alchemyst->open($tempfile)->turnInto($tempdest, $specification)->close();
     } catch (Exception $e) {
         $this->logger->addInfo(sprintf('A media-alchemyst exception occured %s', $e->getMessage()));
         return new Result($job->handle(), $query->getUuid(), $job->workload(), null, $this->workerName, $start, microtime(true), array(), array(sprintf('A media-alchemyst exception occured %s', $e->getMessage())));
     } catch (\Exception $e) {
         $this->logger->addInfo(sprintf('An unexpected exception occured %s', $e->getMessage()));
         return new Result($job->handle(), $query->getUuid(), $job->workload(), null, $this->workerName, $start, microtime(true), array(), array(sprintf('An unexpected exception occured %s', $e->getMessage())));
     }
     $result = new Result($job->handle(), $query->getUuid(), $job->workload(), file_get_contents($tempdest), $this->workerName, $start, microtime(true));
     unlink($tempfile);
     unlink($tempdest);
     $this->logger->addInfo('Conversion successfull');
     $job->sendStatus(100, 100);
     return $result;
 }
Beispiel #3
0
 function sleepFunc(\GearmanJob $job)
 {
     $sleepSeconds = intval(unserialize($job->workload()));
     $this->log('in sleepFunc() - sleeping for ' . $sleepSeconds . ' seconds');
     sleep($sleepSeconds);
     $job->sendComplete('completed');
 }
Beispiel #4
0
 /**
  * {@inheritdoc}
  */
 public function process(\GearmanJob $job)
 {
     $start = microtime(true);
     $command = json_decode($job->workload(), true);
     $result = $this->executeCommand($command);
     $result['elapsed'] = microtime(true) - $start;
     return json_encode($result);
 }
Beispiel #5
0
 public function csvHandler(GearmanJob $job)
 {
     $mass = unserialize($job->workload());
     self::$count = count($mass[1]) - 1;
     usort($mass, array('MyClass', 'cmp'));
     $off = array_slice($mass, 0, 1000);
     self::$collection[] = $off;
 }
Beispiel #6
0
 /**
  * @param \GearmanJob $job
  * @return \filsh\yii2\gearman\JobWorkload
  */
 protected function getWorkload(\GearmanJob $job)
 {
     $workload = null;
     if ($data = $job->workload()) {
         $workload = unserialize($data);
     }
     return $workload;
 }
 /**
  * Test method to run as a job
  *
  * @param \GearmanJob $job Object with job parameters
  *
  * @return boolean
  *
  * @Gearman\Job(
  *     defaultMethod = "doLowBackground"
  * )
  */
 public function testB(\GearmanJob $job)
 {
     $workload = $job->workload();
     echo "Received job: " . $job->handle() . "\n";
     echo "Workload: {$workload}\n";
     $result = strrev($workload);
     echo "Result: {$result}\n";
     return $result;
 }
function func(GearmanJob $job)
{
    $data = json_decode($job->workload(), true);
    // 临时关闭Logger
    $tmpEnable = GlobalConfig::$LOGGER_ENABLE;
    GlobalConfig::$LOGGER_ENABLE = false;
    LoggerInterface::save($data);
    GlobalConfig::$LOGGER_ENABLE = $tmpEnable;
}
 /**
  * Test method to run as a job
  *
  * @param \GearmanJob $job Object with job parameters
  *
  * @return boolean
  *
  * @Gearman\Job(
  *     name = "sendNotificationsToUsers",
  *     description = "Sends a list users an awesome notification"
  * )
  */
 public function sendNotificationsToUsers(\GearmanJob $job)
 {
     // Get the data we put in for the job previously.
     $data = json_decode($job->workload(), true);
     //        foreach ($data['user_ids'] as $userId)
     //        {
     error_log($userId);
     //        }
 }
 public function execute(\GearmanJob $job = null)
 {
     $data = unserialize($job->workload());
     $params = $data->getParams();
     $mail = MailGearman::findOne($params['data']);
     Yii::$app->mailer->compose()->setTo($mail->to)->setFrom($mail->from)->setSubject($mail->subject)->setTextBody($mail->message)->send();
     $mail->status = 1;
     $mail->save();
     return true;
 }
 public function run(\GearmanJob $job, &$log)
 {
     $url = GearmanToolsUtils::unpackMessage($job->workload());
     $this->processorPool->process($url);
     $result = ['url' => $url, 'extractedUrls' => $this->processorPool->getExtractedUrls()];
     $extractedurlsCount = count($this->processorPool->getExtractedUrls());
     $log[] = "url (D={$url->getDepth()}) (S={$url->getStatus()}) (+={$extractedurlsCount}): {$url->getUrl()}";
     $result = GearmanToolsUtils::packMessage($result);
     return $result;
 }
Beispiel #12
0
 /**
  * @return null
  */
 protected function initBasicParams()
 {
     $this->adaptedService->setParams(unserialize($this->job->workload()));
     if ($this->adaptedService->getParams() instanceof AdaptedDto) {
         $this->adaptedService->getExecutionDto()->setTaskId($this->adaptedService->getParams()->getTaskId());
     } else {
         $params = $this->adaptedService->getParams();
         $this->adaptedService->getExecutionDto()->setTaskId($params['task_id']);
     }
     return null;
 }
function func(GearmanJob $job)
{
    $params = json_decode($job->workload(), true);
    $config = Arr::get('config', $params, array());
    $subject = Arr::get('subject', $params, '');
    $body = Arr::get('body', $params, '');
    $to = Arr::get('to', $params, '');
    $cc = Arr::get('cc', $params, '');
    $bcc = Arr::get('bcc', $params, '');
    $email = new EmailClient($config);
    $email->send($subject, $body, $to, $cc, $bcc);
}
 public function regenerate(\GearmanJob $job)
 {
     $workload = json_decode($job->workload());
     $post = $workload->post;
     if ($this->isRevision($post)) {
         return;
     }
     echo $this->getDate() . " Regenerating supertags due to change in post #{$post->ID} of type {$post->post_type}...";
     $vocabFetcher = new \Supertags\VocabFetcher($this->logger);
     $vocabFetcher->getVocabTerms(true, $post->post_type);
     echo "done.\n";
 }
 public function work(GearmanJob $job)
 {
     $workload = $job->workload();
     $json = json_decode($workload, true);
     if (!json_last_error()) {
         $workload = $json;
     }
     $eventManager = new CakeEventManager();
     $eventManager->dispatch(new CakeEvent('Gearman.beforeWork', $this, $workload));
     $data = call_user_func($this->_workers[$job->functionName()], $job, $workload);
     $eventManager->dispatch(new CakeEvent('Gearman.afterWork', $this, $workload));
     return $data;
 }
Beispiel #16
0
function testEmail(GearmanJob $job)
{
    global $client, $output;
    $email = $job->workload();
    $result = $client->checkEmail($email);
    if ($result) {
        if ($output->flock(LOCK_EX)) {
            $output->fwrite($email . PHP_EOL);
            $output->flock(LOCK_UN);
        }
    }
    return json_encode(['email' => $email, 'status' => $result]);
}
Beispiel #17
0
 public function process(\GearmanJob $job)
 {
     /*
      * @todo Schema validation
      */
     $this->workload = json_decode($job->workload(), true);
     $this->logger->info('Task accepted', ['function' => $this->function]);
     if (!$this->workload) {
         $this->logger->warning('Workload is empty', ['function' => $this->function]);
         return false;
     }
     return true;
 }
 public function initManager(\GearmanJob $job)
 {
     $this->job = $job;
     $this->gearmanDto = unserialize($job->workload());
     $this->processManager = ProcessManagerFactory::getProcessManager($this->gearmanDto->getManagerType());
     $this->processManager->setJob($job);
     $this->processManager->setGearmanDto($this->gearmanDto);
     try {
         $this->processManager->manage();
     } catch (\Exception $e) {
         $errorMessage = "Gearman process manager die with exception: " . $e->getMessage() . "| gearmanDto: " . serialize($this->gearmanDto);
         $this->logger->warning($errorMessage);
         $this->processManager->getExecutionDto()->setErrorMessage($errorMessage);
         die;
     }
     return null;
 }
Beispiel #19
0
 public function doConvert(GearmanJob $job)
 {
     $workload = Job::fromArray(json_decode($job->workload(), true));
     $this->_logger->gotJob($workload);
     if (!$this->_validator->isValid($workload)) {
         return static::FAILED;
     }
     foreach ($workload->getResolutionList() as list($width, $height, $applicableTo)) {
         $image = new Imagick($workload->sourceFileInfo()->getRealPath());
         if (!in_array($this->_getSourceType($image), $applicableTo)) {
             continue;
         }
         $image->resizeImage($width, $height, Imagick::FILTER_CATROM, 1, true);
         $image->writeImage($workload->formatTargetFilePath($width, $height));
     }
     //    unlink($workload->sourceFileInfo()->getRealPath());
     return json_encode($workload);
 }
 public function run(\GearmanJob $job)
 {
     $url = GearmanToolsUtils::unpackMessage($job->workload());
     $error = 0;
     try {
         $this->processorPool->process($url);
         $extractedUrlsCount = count($this->processorPool->getExtractedUrls());
         $message = "{$url->getUrl()} / depth: {$url->getDepth()} / status: {$url->getStatus()} / extracted: {$extractedUrlsCount}";
     } catch (\Exception $e) {
         $message = "Failed to process url [{$url->getId()}] \"{$url->getUrl()}\": {$e->getMessage()}";
         $error = $e->getCode();
         $error = $error === 0 ? -1 : $error;
     }
     $result = ['url' => $url, 'extractedUrls' => $this->processorPool->getExtractedUrls(), 'error' => $error, 'message' => $message];
     $this->logger->info($message);
     $result = GearmanToolsUtils::packMessage($result);
     return $result;
 }
Beispiel #21
0
 /**
  * Realizuje wysyłkę wiadomości w pakiecie
  * @param GearmanJob $job
  */
 public function sendpackage(GearmanJob $job)
 {
     $params = json_decode($job->workload());
     list($mode, $packageDataId, $packageId) = $params;
     $package = new Logic_Package($mode);
     $wsPackage = new WsPackage();
     $wsPackageRow = $wsPackage->findOne($packageId);
     $package->updatePackageStatus($packageId, WsPackageStatus::STATUS_STARTED);
     $wsServiceSetRow = $wsPackageRow->findParentRow('WsServiceSet');
     $rawData = $package->getRawDataToSend($packageDataId);
     $client = Logic_Client::getInstanceByUser($package->getLastPackageStatus($packageId)->created_by);
     $package->updatePackageDataStatus($packageDataId, array('id_status' => WsPackageStatus::STATUS_STARTED));
     $service;
     switch ($mode) {
         case Logic_Package::SMS_MODE:
             $loadBalancer = $client->getLoadBalancer(Wsclient::GROUP_SMS, $wsServiceSetRow->ws_service_group_id);
             $hasErrors = false;
             $service = $loadBalancer->getService();
             do {
                 if (null === $service) {
                     $package->updatePackageDataStatus($packageDataId, array('id_status' => WsPackageStatus::STATUS_ERROR));
                     return $job->sendException("Unable to get service! Check backup service!");
                 }
                 $sms = new Logic_Sms($service, $wsPackageRow->ip, $wsServiceSetRow->id);
                 try {
                     if ($wsPackageRow->getLastStatus()->id_status == WsPackageStatus::STATUS_STARTED) {
                         $response = $sms->package($rawData, $packageId);
                         $package->updatePackageDataStatus($packageDataId, array('id_status' => WsPackageStatus::STATUS_SENT, 'external_package_id' => $response->packageId, 'ws_service_id' => $service->id));
                         $package->confirmPackageSend($wsPackageRow);
                     }
                     break;
                 } catch (Exception $exc) {
                     $hasErrors = true;
                     $package->updatePackageDataStatus($packageDataId, array('id_status' => WsPackageStatus::STATUS_ERROR));
                     $service = $loadBalancer->getService();
                     sleep(1);
                 }
             } while (true === $hasErrors || !(true === is_object($response) && true === property_exists($response, 'packageId')));
             break;
     }
     unset($client);
 }
Beispiel #22
0
 /**
  * Executes a [Request] object and returns the response
  * 
  *      // Create a request
  *      $request = Request::factory('/users/load/1');
  * 
  *      // Execute the request
  *      $response = Request_Async_Gearman::execute_request($request);
  * 
  *  Used as a callback by Request_Async_Gearman to handle the request
  *  processing.
  * 
  * @param   Kohana_Request  request to process
  * @return  Kohana_Response  the response from the request
  */
 public static function execute_request(GearmanJob $job)
 {
     // Unserialise the request
     $request = unserialize($job->workload());
     // Send starting status
     $job->sendStatus(1, 2);
     // Encapsulate request execution
     try {
         // Get the response
         $response = $request->execute()->headers('X-Request-Uri', $request->uri());
     } catch (Exception $e) {
         // Send the exception to Gearman
         $job->sendException($e->getMessage());
         return;
     }
     // Send complete status
     $job->sendStatus(2, 2);
     // Send the response
     $job->sendData(serialize($response));
 }
Beispiel #23
0
 public final function execute(\GearmanJob $job)
 {
     $this->logger->addInfo(sprintf('Receiving job handle %s (%s)', $job->handle(), $job->unique()));
     try {
         $query = unserialize($job->workload());
         $this->logger->addInfo('Workload unserialized');
         if (!$query instanceof Query) {
             throw new RuntimeException('Expecting a Gloubster Query');
         }
         $this->logger->addInfo('Query OK');
     } catch (RuntimeException $e) {
         $this->logger->addError(sprintf('Error while getting the job : %s', $e->getMessage()));
         return;
     }
     try {
         $query->getDelivery($this->deliveryFactory, $this->configuration)->deliver($query->getUuid(), $this->processQuery($job, $query));
     } catch (\Exception $e) {
         $this->logger->addError(sprintf('Error while processing : %s', $e->getMessage()));
     }
 }
Beispiel #24
0
 /**
  * 
  * @param type $mode
  * @return type
  * 
  */
 public function setup(GearmanJob $job)
 {
     $params = json_decode($job->workload());
     $mode = $params[0];
     $packageId = $params[1];
     $package = new Logic_Package($mode);
     try {
         $packagesArray = $package->getNewPackages(1, $packageId);
     } catch (Exception $exc) {
         throw new Exception("Could not get ready packages!", $exc->getCode(), $exc);
     }
     if (count($packagesArray) === 0) {
         throw new Exception('No packages found!');
     }
     foreach ($packagesArray as $packageItem) {
         try {
             $package->loadPackage($packageItem);
         } catch (Exception $exc) {
             throw new Exception($exc->getMessage());
         }
         $package->updatePackageStatus($packageItem['id'], WsPackageStatus::STATUS_READY);
     }
 }
 /**
  * @Gearman\Job()
  */
 public function apiUpdate(\GearmanJob $job)
 {
     $apiCallId = '?';
     try {
         $apiCallId = $job->workload();
         $this->entityManager->getConnection()->beginTransaction();
         $this->apiUpdater->update($apiCallId);
         $this->entityManager->flush();
         $this->entityManager->getConnection()->commit();
     } catch (\Exception $e) {
         $this->entityManager->getConnection()->rollback();
         $this->entityManager->close();
         $details = array('callId' => $apiCallId, 'exception' => $e);
         if (strstr($e->getMessage(), '1213 Deadlock found when trying to get lock; try restarting transaction')) {
             $this->logger->info('{callId}: Deadlock', $details);
         } elseif (strstr($e->getMessage(), '1205 Lock wait timeout exceeded; try restarting transaction')) {
             $this->logger->info('{callId}: Lock wait timeout', $details);
         } else {
             $this->logger->critical('{callId}: Unhandled exception', $details);
         }
         throw $e;
     }
 }
Beispiel #26
0
 /**
  * @param GearmanJob $job
  * @return string|null
  * @throws CM_Exception_Nonexistent
  */
 public function __executeGearman(GearmanJob $job)
 {
     $workload = $job->workload();
     try {
         $params = CM_Params::factory(CM_Params::jsonDecode($workload), true);
     } catch (CM_Exception_Nonexistent $ex) {
         throw new CM_Exception_Nonexistent('Cannot decode workload for Job `' . get_class($this) . '`: Original exception message `' . $ex->getMessage() . '`', CM_Exception::WARN);
     }
     return CM_Params::encode($this->_executeJob($params), true);
 }
 /**
  * Wrapper function to retrieve the workload
  * @param \GearmanJob $job
  */
 protected function work($job)
 {
     $this->workload = unserialize($job->workload());
 }
 /**
  * Memperbarui kepulangan siswa.
  *
  * @param \GearmanJob $job
  *
  * @Gearman\Job(
  *     name = "pembaruan",
  *     description = "Memperbarui kepulangan siswa."
  * )
  *
  * @return boolean
  */
 public function pembaruan(\GearmanJob $job)
 {
     $em = $this->entityManager;
     $data = unserialize($job->workload());
     $paksa = $data['paksa'];
     $perulangan = $data['perulangan'];
     $logFile = $data['log_file'];
     /* @var $waktuSekarang \DateTime */
     $waktuSekarang = $data['waktu_sekarang'];
     $jam = $waktuSekarang->format('H:i') . ':00';
     $mingguanHariKe = $waktuSekarang->format('N');
     $bulananHariKe = $waktuSekarang->format('j');
     /* @var $sekolah Sekolah */
     $sekolah = $em->getRepository('LanggasSisdikBundle:Sekolah')->find($data['sekolah']);
     /* @var $prosesLog ProsesLogKepulangan */
     $prosesLog = $em->getRepository('LanggasSisdikBundle:ProsesLogKepulangan')->find($data['proses_log']);
     $prosesLog->setStatusAntrian('b-sedang-dikerjakan');
     $em->persist($prosesLog);
     $em->flush();
     $jumlahLogDiproses = 0;
     $querybuilder = $em->createQueryBuilder()->select('jadwal')->from('LanggasSisdikBundle:JadwalKepulangan', 'jadwal')->leftJoin('jadwal.tahunAkademik', 'tahunAkademik')->andWhere('jadwal.sekolah = :sekolah')->andWhere('jadwal.paramstatusHinggaJam <= :jam')->andWhere('jadwal.perulangan = :perulangan')->andWhere('jadwal.permulaan = :permulaan')->andWhere('jadwal.otomatisTerhubungMesin = :terhubung')->andWhere('tahunAkademik.aktif = :aktif')->setParameter('sekolah', $sekolah)->setParameter('jam', $jam)->setParameter('perulangan', $perulangan)->setParameter('permulaan', false)->setParameter('aktif', true)->setParameter('terhubung', true)->orderBy('jadwal.paramstatusHinggaJam', 'ASC');
     if ($perulangan == 'b-mingguan') {
         $querybuilder->andWhere('jadwal.mingguanHariKe = :harike')->setParameter('harike', $mingguanHariKe);
     } elseif ($perulangan == 'c-bulanan') {
         $querybuilder->andWhere('jadwal.bulananHariKe = :tanggalke')->setParameter('tanggalke', $bulananHariKe);
     }
     $jadwalKepulangan = $querybuilder->getQuery()->getResult();
     foreach ($jadwalKepulangan as $jadwal) {
         if (!(is_object($jadwal) && $jadwal instanceof JadwalKepulangan)) {
             continue;
         }
         $dariJam = $jadwal->getParamstatusDariJam();
         $hinggaJam = $jadwal->getParamstatusHinggaJam();
         $tanggalJadwalDari = new \DateTime($waktuSekarang->format('Y-m-d') . " {$dariJam}");
         $tanggalJadwalHingga = new \DateTime($waktuSekarang->format('Y-m-d') . " {$hinggaJam}");
         $targetFile = self::TMP_DIR . DIRECTORY_SEPARATOR . $sekolah->getId() . '-sisdik-' . uniqid(mt_rand(), true) . '.gz';
         if (!@copy($logFile, $targetFile)) {
             continue;
         }
         $siswaTerbarui = $em->createQueryBuilder()->select('siswa.nomorIndukSistem')->from('LanggasSisdikBundle:KepulanganSiswa', 'kepulangan')->leftJoin('kepulangan.siswa', 'siswa')->where('kepulangan.sekolah = :sekolah')->andWhere('kepulangan.tanggal = :tanggal')->andWhere('kepulangan.permulaan = :permulaan OR kepulangan.tervalidasi = :tervalidasi')->setParameter('sekolah', $sekolah)->setParameter('tanggal', $waktuSekarang->format('Y-m-d'))->setParameter('permulaan', false)->setParameter('tervalidasi', true)->getQuery()->getArrayResult();
         $nomorTerproses = '';
         foreach ($siswaTerbarui as $val) {
             $nomorTerproses .= $val['nomorIndukSistem'] . '|';
         }
         $nomorTerproses = preg_replace('/\\|$/', '', $nomorTerproses);
         exec("gunzip --force {$targetFile}");
         $extractedFile = substr($targetFile, 0, -3);
         if (strstr($targetFile, 'json') !== false) {
             $buffer = file_get_contents($extractedFile);
             $logKepulangan = json_decode($buffer, true);
             foreach ($logKepulangan as $item) {
                 $logTanggal = new \DateTime($item['datetime']);
                 // +60 detik perbedaan
                 if (!($logTanggal->getTimestamp() >= $tanggalJadwalDari->getTimestamp() && $logTanggal->getTimestamp() <= $tanggalJadwalHingga->getTimestamp() + 60)) {
                     continue;
                 }
                 if ($logTanggal->format('Ymd') != $waktuSekarang->format('Ymd')) {
                     continue;
                 }
                 $siswa = $em->getRepository('LanggasSisdikBundle:Siswa')->findOneBy(['nomorIndukSistem' => $item['id']]);
                 if (is_object($siswa) && $siswa instanceof Siswa) {
                     $kepulanganSiswa = $em->getRepository('LanggasSisdikBundle:KepulanganSiswa')->findOneBy(['sekolah' => $sekolah, 'tahunAkademik' => $jadwal->getTahunAkademik(), 'kelas' => $jadwal->getKelas(), 'siswa' => $siswa, 'tanggal' => $waktuSekarang, 'permulaan' => true]);
                     if (is_object($kepulanganSiswa) && $kepulanganSiswa instanceof KepulanganSiswa) {
                         try {
                             $em->lock($kepulanganSiswa, LockMode::OPTIMISTIC, $kepulanganSiswa->getVersi());
                             $kepulanganSiswa->setPermulaan(false);
                             $kepulanganSiswa->setStatusKepulangan($jadwal->getStatusKepulangan());
                             $kepulanganSiswa->setJam($logTanggal->format('H:i:s'));
                             $kepulanganSiswa->setTerprosesOtomatis(true);
                             $em->persist($kepulanganSiswa);
                             $em->flush();
                             $jumlahLogDiproses++;
                         } catch (OptimisticLockException $e) {
                             $this->logger->addNotice($e);
                         }
                     }
                 }
             }
             $prosesKepulanganSiswa = $em->getRepository('LanggasSisdikBundle:ProsesKepulanganSiswa')->findOneBy(['sekolah' => $sekolah, 'tahunAkademik' => $jadwal->getTahunAkademik(), 'kelas' => $jadwal->getKelas(), 'tanggal' => $waktuSekarang, 'berhasilDiperbaruiMesin' => false]);
             if (is_object($prosesKepulanganSiswa) && $prosesKepulanganSiswa instanceof ProsesKepulanganSiswa) {
                 $prosesKepulanganSiswa->setBerhasilDiperbaruiMesin(true);
                 $em->persist($prosesKepulanganSiswa);
                 $em->flush();
             }
         } else {
             if ($nomorTerproses != '') {
                 exec("sed -i -E '/{$nomorTerproses}/d' {$extractedFile}");
             }
             exec("sed -i -n '/<.*>/,\$p' {$extractedFile}");
             $buffer = file_get_contents($extractedFile);
             $buffer = preg_replace("/\\s+/", ' ', trim($buffer));
             $xmlstring = "<?xml version='1.0'?>\n" . $buffer;
             $xmlobject = @simplexml_load_string($xmlstring);
             if ($xmlobject) {
                 foreach ($xmlobject->xpath('Row') as $item) {
                     $logTanggal = new \DateTime($item->DateTime);
                     // +60 detik perbedaan
                     if (!($logTanggal->getTimestamp() >= $tanggalJadwalDari->getTimestamp() && $logTanggal->getTimestamp() <= $tanggalJadwalHingga->getTimestamp() + 60)) {
                         continue;
                     }
                     if ($logTanggal->format('Ymd') != $waktuSekarang->format('Ymd')) {
                         continue;
                     }
                     $siswa = $em->getRepository('LanggasSisdikBundle:Siswa')->findOneBy(['nomorIndukSistem' => $item->PIN]);
                     if (is_object($siswa) && $siswa instanceof Siswa) {
                         $kepulanganSiswa = $em->getRepository('LanggasSisdikBundle:KepulanganSiswa')->findOneBy(['sekolah' => $sekolah, 'tahunAkademik' => $jadwal->getTahunAkademik(), 'kelas' => $jadwal->getKelas(), 'siswa' => $siswa, 'tanggal' => $waktuSekarang, 'permulaan' => true]);
                         if (is_object($kepulanganSiswa) && $kepulanganSiswa instanceof KepulanganSiswa) {
                             try {
                                 $em->lock($kepulanganSiswa, LockMode::OPTIMISTIC, $kepulanganSiswa->getVersi());
                                 $kepulanganSiswa->setPermulaan(false);
                                 $kepulanganSiswa->setStatusKepulangan($jadwal->getStatusKepulangan());
                                 $kepulanganSiswa->setJam($logTanggal->format('H:i:s'));
                                 $kepulanganSiswa->setTerprosesOtomatis(true);
                                 $em->persist($kepulanganSiswa);
                                 $em->flush();
                                 $jumlahLogDiproses++;
                             } catch (OptimisticLockException $e) {
                                 $this->logger->addNotice($e);
                             }
                         }
                     }
                 }
                 $prosesKepulanganSiswa = $em->getRepository('LanggasSisdikBundle:ProsesKepulanganSiswa')->findOneBy(['sekolah' => $sekolah, 'tahunAkademik' => $jadwal->getTahunAkademik(), 'kelas' => $jadwal->getKelas(), 'tanggal' => $waktuSekarang, 'berhasilDiperbaruiMesin' => false]);
                 if (is_object($prosesKepulanganSiswa) && $prosesKepulanganSiswa instanceof ProsesKepulanganSiswa) {
                     $prosesKepulanganSiswa->setBerhasilDiperbaruiMesin(true);
                     $em->persist($prosesKepulanganSiswa);
                     $em->flush();
                 }
             }
         }
         @unlink($extractedFile);
     }
     $prosesLog->setStatusAntrian('c-selesai');
     $prosesLog->setAkhirProses(new \DateTime());
     $prosesLog->setJumlahLogDiproses($jumlahLogDiproses);
     $em->persist($prosesLog);
     $em->flush();
     return true;
 }
Beispiel #29
0
 /**
  * method to run as a job
  *
  * @param \GearmanJob $job Object with job parameters
  *
  * @return boolean
  *
  * @Gearman\Job(
  *     name = "push_http",
  *     description = "This pushes messages to gcm via http")
  */
 public function pushViaHttp(\GearmanJob $job)
 {
     $random = $job->workload();
     //do update the leaderboard
     //broadcast this to all the users in current message's user's location
     $em = $this->doctrine->getManager();
     $messageRepo = $em->getRepository('LollypopGearBundle:Message');
     $message = $messageRepo->findOneBy(array('uri' => $random));
     $board = $message->getBoard();
     $userRegId = $message->getGcmReg()->getId();
     $gcmRegIDRepo = $em->getRepository('LollypopGearBundle:GCMRegID');
     $page = 1;
     while (true) {
         $registrationIds = [];
         $gcmRegIDs = $gcmRegIDRepo->getRegIdsOfBoard($board, [$userRegId], $page);
         if (empty($gcmRegIDs)) {
             break;
         }
         foreach ($gcmRegIDs as $regId) {
             $registrationIds[] = $regId['value'];
         }
         //get receipents from the message and push using pusher
         $result = $this->pusher->broadcast($registrationIds, array('t' => 'm', 's_id' => $message->getUri(), 'l' => $message->getGcmReg()->getUser()->getCurrentLocation()->getGeoHash(), 'c' => $message->getContent()), 'message', true, 0, 'com.abbiya.broadr');
         //parse through the result and update gcm reg ids according to the pusher service
         if (!empty($result)) {
             $em = $this->doctrine->getManager();
             $GCMRegIDRepo = $em->getRepository('LollypopGearBundle:GCMRegID');
             if (isset($result[GCMRegID::NEW_REG_IDS])) {
                 //Update $oldRegistrationId to $newRegistrationId in DB
                 $newRegIds = (array) $result[GCMRegID::NEW_REG_IDS];
                 foreach ($newRegIds as $oldKey => $newKey) {
                     $oldRegIdObj = $GCMRegIDRepo->findOneBy(array('value' => trim($oldKey)));
                     $newRegIdObj = $GCMRegIDRepo->findOneBy(array('value' => trim($newKey)));
                     if ($oldRegIdObj && $newRegIdObj) {
                         $messageRepo = $em->getRepository('LollypopGearBundle:Message');
                         $messages = $messageRepo->findBy(array('gcm_reg' => $oldRegIdObj));
                         foreach ($messages as $message) {
                             $message->setGcmReg($newRegIdObj);
                         }
                         $em->flush();
                         $em->remove($oldRegIdObj);
                     }
                 }
             }
             if (isset($result[GCMRegID::INVALID_REG_IDS])) {
                 //Remove $invalidRegistrationId from DB
                 $invalidRegIds = (array) $result[GCMRegID::INVALID_REG_IDS];
                 foreach ($invalidRegIds as $invalidRegId) {
                     $this->logger->info('Hola: invalid ' . $invalidRegId);
                     $regIdObj = $GCMRegIDRepo->findOneBy(array('value' => trim($invalidRegId)));
                     if ($regIdObj) {
                         $messages = $messageRepo->findBy(array('gcm_reg' => $regIdObj));
                         foreach ($messages as $message) {
                             $message->setGcmReg(null);
                         }
                         $em->flush();
                         $em->remove($regIdObj);
                     }
                 }
             }
             if (isset($result[GCMRegID::UNAVAILABLE_REG_IDS])) {
                 //Schedule to resend messages to unavailable devices
                 $unavailableIds = (array) $result[GCMRegID::UNAVAILABLE_REG_IDS];
                 foreach ($unavailableIds as $regId) {
                     $this->logger->info('Hola: unavailable ' . $regId);
                 }
             }
             $em->flush();
         }
         $page++;
     }
 }
Beispiel #30
0
/**
 * 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;
    }
}