serviceFactory = $serviceFactory; $this->entityManager = $entityManager; } public function run(JobData $data): void { $targetId = $data->getTargetId(); if (!$targetId) { throw new Error("No target."); } $service = $this->serviceFactory->create('InboundEmail'); $entity = $this->entityManager->getEntity('InboundEmail', $targetId); if (!$entity) { throw new Error("Job CheckInboundEmails '{$targetId}': InboundEmail does not exist.", -1); } if ($entity->get('status') !== 'Active') { throw new Error("Job CheckInboundEmails '{$targetId}': InboundEmail is not active.", -1); } try { $service->fetchFromMailServer($entity); } catch (Throwable $e) { throw new Error( 'Job CheckInboundEmails ' . $entity->getId() . ': [' . $e->getCode() . '] ' .$e->getMessage() ); } } public function prepare(ScheduledJobData $data, DateTimeImmutable $executeTime): void { $collection = $this->entityManager ->getRDBRepository('InboundEmail') ->where([ 'status' => 'Active', 'useImap' => true, ]) ->find(); foreach ($collection as $entity) { $running = $this->entityManager ->getRDBRepository('Job') ->where([ 'scheduledJobId' => $data->getId(), 'status' => [ JobStatus::RUNNING, JobStatus::READY, ], 'targetType' => 'InboundEmail', 'targetId' => $entity->getId(), ]) ->findOne(); if ($running) { continue; } $countPending = $this->entityManager ->getRDBRepository('Job') ->where([ 'scheduledJobId' => $data->getId(), 'status' => JobStatus::PENDING, 'targetType' => 'InboundEmail', 'targetId' => $entity->getId(), ]) ->count(); if ($countPending > 1) { continue; } $jobEntity = $this->entityManager->getEntity('Job'); $jobEntity->set([ 'name' => $data->getName(), 'scheduledJobId' => $data->getId(), 'executeTime' => $executeTime->format(DateTime::SYSTEM_DATE_TIME_FORMAT), 'targetType' => 'InboundEmail', 'targetId' => $entity->getId(), ]); $this->entityManager->saveEntity($jobEntity); } } }