diff --git a/lib/Cron/Workers/SubscribersEngagementScore.php b/lib/Cron/Workers/SubscribersEngagementScore.php index 4ba59ff6f4..30518b73d4 100644 --- a/lib/Cron/Workers/SubscribersEngagementScore.php +++ b/lib/Cron/Workers/SubscribersEngagementScore.php @@ -28,21 +28,31 @@ class SubscribersEngagementScore extends SimpleWorker { } public function processTaskStrategy(ScheduledTask $task, $timer) { - $subscribers = $this->subscribersRepository->findBy( - ['engagementScoreUpdatedAt' => null], - [], - SubscribersEngagementScore::BATCH_SIZE - ); + $subscribers = $this->subscribersRepository->findByUpdatedScoreNotInLastMonth(SubscribersEngagementScore::BATCH_SIZE); foreach ($subscribers as $subscriber) { $this->statisticsOpensRepository->recalculateSubscriberScore($subscriber); } if ($subscribers) { + $this->scheduleImmediately(); + } else { $this->schedule(); } return true; } - public function getNextRunDate() { + public function scheduleImmediately(): void { + $this->cronWorkerScheduler->schedule(static::TASK_TYPE, $this->getNextRunDateImmediately()); + } + + public function getNextRunDateImmediately(): Carbon { return Carbon::createFromTimestamp($this->wp->currentTime('timestamp')); } + + public function getNextRunDate() { + // random day of the next week + $date = Carbon::createFromTimestamp($this->wp->currentTime('timestamp')); + $date->addDay(); + $date->setTime(mt_rand(0, 23), mt_rand(0, 59)); + return $date; + } } diff --git a/lib/Subscribers/SubscribersRepository.php b/lib/Subscribers/SubscribersRepository.php index 7819d6342b..eb495a66f4 100644 --- a/lib/Subscribers/SubscribersRepository.php +++ b/lib/Subscribers/SubscribersRepository.php @@ -8,6 +8,7 @@ use MailPoet\Entities\SubscriberCustomFieldEntity; use MailPoet\Entities\SubscriberEntity; use MailPoet\Entities\SubscriberSegmentEntity; use MailPoet\WP\Functions as WPFunctions; +use MailPoetVendor\Carbon\Carbon; use MailPoetVendor\Doctrine\DBAL\Connection; use MailPoetVendor\Doctrine\ORM\EntityManager; use MailPoetVendor\Doctrine\ORM\Query\Expr\Join; @@ -292,4 +293,17 @@ class SubscribersRepository extends Repository { } return $this->findOneBy(['wpUserId' => $wpUser->ID]); } + + public function findByUpdatedScoreNotInLastMonth(int $limit): array { + $dateTime = (new Carbon())->subMonths(1); + return $this->entityManager->createQueryBuilder() + ->select('s') + ->from(SubscriberEntity::class, 's') + ->where('s.engagementScoreUpdatedAt IS NULL') + ->orWhere('s.engagementScoreUpdatedAt < :dateTime') + ->setParameter('dateTime', $dateTime) + ->getQuery() + ->setMaxResults($limit) + ->getResult(); + } }