Pass cron worker timer in process() method instead of a constructor

[MAILPOET-2538]
This commit is contained in:
Jan Jakeš
2019-11-19 12:58:01 +01:00
committed by Jack Kitterhing
parent afecae15f5
commit 382df5e034
31 changed files with 197 additions and 244 deletions

View File

@ -26,7 +26,7 @@ class Daemon {
$errors = []; $errors = [];
foreach ($this->getWorkers() as $worker) { foreach ($this->getWorkers() as $worker) {
try { try {
$worker->process(); $worker->process($this->timer);
} catch (\Exception $e) { } catch (\Exception $e) {
$worker_class_name_parts = explode('\\', get_class($worker)); $worker_class_name_parts = explode('\\', get_class($worker));
$errors[] = [ $errors[] = [
@ -45,21 +45,21 @@ class Daemon {
} }
private function getWorkers() { private function getWorkers() {
yield $this->workers_factory->createMigrationWorker($this->timer); yield $this->workers_factory->createMigrationWorker();
yield $this->workers_factory->createStatsNotificationsWorker($this->timer); yield $this->workers_factory->createStatsNotificationsWorker();
yield $this->workers_factory->createScheduleWorker($this->timer); yield $this->workers_factory->createScheduleWorker();
yield $this->workers_factory->createQueueWorker($this->timer); yield $this->workers_factory->createQueueWorker();
yield $this->workers_factory->createSendingServiceKeyCheckWorker($this->timer); yield $this->workers_factory->createSendingServiceKeyCheckWorker();
yield $this->workers_factory->createPremiumKeyCheckWorker($this->timer); yield $this->workers_factory->createPremiumKeyCheckWorker();
yield $this->workers_factory->createBounceWorker($this->timer); yield $this->workers_factory->createBounceWorker();
yield $this->workers_factory->createExportFilesCleanupWorker($this->timer); yield $this->workers_factory->createExportFilesCleanupWorker();
yield $this->workers_factory->createBeamerkWorker($this->timer); yield $this->workers_factory->createBeamerkWorker();
yield $this->workers_factory->createInactiveSubscribersWorker($this->timer); yield $this->workers_factory->createInactiveSubscribersWorker();
yield $this->workers_factory->createUnsubscribeTokensWorker($this->timer); yield $this->workers_factory->createUnsubscribeTokensWorker();
yield $this->workers_factory->createWooCommerceSyncWorker($this->timer); yield $this->workers_factory->createWooCommerceSyncWorker();
yield $this->workers_factory->createAuthorizedSendingEmailsCheckWorker($this->timer); yield $this->workers_factory->createAuthorizedSendingEmailsCheckWorker();
yield $this->workers_factory->createWooCommercePastOrdersWorker($this->timer); yield $this->workers_factory->createWooCommercePastOrdersWorker();
yield $this->workers_factory->createStatsNotificationsWorkerForAutomatedEmails($this->timer); yield $this->workers_factory->createStatsNotificationsWorkerForAutomatedEmails();
yield $this->workers_factory->createSubscriberLinkTokensWorker($this->timer); yield $this->workers_factory->createSubscriberLinkTokensWorker();
} }
} }

View File

@ -13,16 +13,16 @@ class AuthorizedSendingEmailsCheck extends SimpleWorker {
/** @var AuthorizedEmailsController */ /** @var AuthorizedEmailsController */
private $authorized_emails_controller; private $authorized_emails_controller;
function __construct(AuthorizedEmailsController $authorized_emails_controller, $timer = false) { function __construct(AuthorizedEmailsController $authorized_emails_controller) {
$this->authorized_emails_controller = $authorized_emails_controller; $this->authorized_emails_controller = $authorized_emails_controller;
parent::__construct($timer); parent::__construct();
} }
function checkProcessingRequirements() { function checkProcessingRequirements() {
return Bridge::isMPSendingServiceEnabled(); return Bridge::isMPSendingServiceEnabled();
} }
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
$this->authorized_emails_controller->checkAuthorizedEmailAddresses(); $this->authorized_emails_controller->checkAuthorizedEmailAddresses();
return true; return true;
} }

View File

@ -18,13 +18,13 @@ class Beamer extends SimpleWorker {
/** @var WPFunctions */ /** @var WPFunctions */
private $wp; private $wp;
function __construct(SettingsController $settings, WPFunctions $wp, $timer = false) { function __construct(SettingsController $settings, WPFunctions $wp) {
parent::__construct($timer); parent::__construct();
$this->settings = $settings; $this->settings = $settings;
$this->wp = $wp; $this->wp = $wp;
} }
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
return $this->setLastAnnouncementDate(); return $this->setLastAnnouncementDate();
} }

View File

@ -29,9 +29,9 @@ class Bounce extends SimpleWorker {
/** @var SettingsController */ /** @var SettingsController */
private $settings; private $settings;
function __construct(SettingsController $settings, $timer = false) { function __construct(SettingsController $settings) {
$this->settings = $settings; $this->settings = $settings;
parent::__construct($timer); parent::__construct();
} }
function init() { function init() {
@ -44,7 +44,7 @@ class Bounce extends SimpleWorker {
return Bridge::isMPSendingServiceEnabled(); return Bridge::isMPSendingServiceEnabled();
} }
function prepareTaskStrategy(ScheduledTask $task) { function prepareTaskStrategy(ScheduledTask $task, $timer) {
BounceTask::prepareSubscribers($task); BounceTask::prepareSubscribers($task);
if (!ScheduledTaskSubscriber::getUnprocessedCount($task->id)) { if (!ScheduledTaskSubscriber::getUnprocessedCount($task->id)) {
@ -54,7 +54,7 @@ class Bounce extends SimpleWorker {
return true; return true;
} }
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
$subscriber_batches = new BatchIterator($task->id, self::BATCH_SIZE); $subscriber_batches = new BatchIterator($task->id, self::BATCH_SIZE);
if (count($subscriber_batches) === 0) { if (count($subscriber_batches) === 0) {
@ -66,7 +66,7 @@ class Bounce extends SimpleWorker {
foreach ($subscriber_batches as $subscribers_to_process_ids) { foreach ($subscriber_batches as $subscribers_to_process_ids) {
// abort if execution limit is reached // abort if execution limit is reached
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
$subscriber_emails = Subscriber::select('email') $subscriber_emails = Subscriber::select('email')
->whereIn('id', $subscribers_to_process_ids) ->whereIn('id', $subscribers_to_process_ids)

View File

@ -10,7 +10,7 @@ class ExportFilesCleanup extends SimpleWorker {
const TASK_TYPE = 'export_files_cleanup'; const TASK_TYPE = 'export_files_cleanup';
const DELETE_FILES_AFTER_X_DAYS = 1; const DELETE_FILES_AFTER_X_DAYS = 1;
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
$iterator = new \GlobIterator(Export::getExportPath() . '/' . Export::getFilePrefix() . '*.*'); $iterator = new \GlobIterator(Export::getExportPath() . '/' . Export::getFilePrefix() . '*.*');
foreach ($iterator as $file) { foreach ($iterator as $file) {
if (is_string($file)) { if (is_string($file)) {

View File

@ -21,16 +21,15 @@ class InactiveSubscribers extends SimpleWorker {
function __construct( function __construct(
InactiveSubscribersController $inactive_subscribers_controller, InactiveSubscribersController $inactive_subscribers_controller,
SettingsController $settings, SettingsController $settings
$timer = false
) { ) {
$this->inactive_subscribers_controller = $inactive_subscribers_controller; $this->inactive_subscribers_controller = $inactive_subscribers_controller;
$this->settings = $settings; $this->settings = $settings;
parent::__construct($timer); parent::__construct();
} }
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
$tracking_enabled = (bool)$this->settings->get('tracking.enabled'); $tracking_enabled = (bool)$this->settings->get('tracking.enabled');
if (!$tracking_enabled) { if (!$tracking_enabled) {
$this->schedule(); $this->schedule();
@ -55,10 +54,10 @@ class InactiveSubscribers extends SimpleWorker {
$last_subscriber_id += self::BATCH_SIZE; $last_subscriber_id += self::BATCH_SIZE;
$task->meta = ['last_subscriber_id' => $last_subscriber_id]; $task->meta = ['last_subscriber_id' => $last_subscriber_id];
$task->save(); $task->save();
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
}; };
while ($this->inactive_subscribers_controller->markActiveSubscribers($days_to_inactive, self::BATCH_SIZE) === self::BATCH_SIZE) { while ($this->inactive_subscribers_controller->markActiveSubscribers($days_to_inactive, self::BATCH_SIZE) === self::BATCH_SIZE) {
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
}; };
$this->schedule(); $this->schedule();
return true; return true;

View File

@ -15,7 +15,7 @@ abstract class KeyCheckWorker extends SimpleWorker {
} }
} }
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
try { try {
$result = $this->checkKey(); $result = $this->checkKey();
} catch (\Exception $e) { } catch (\Exception $e) {

View File

@ -11,9 +11,9 @@ class PremiumKeyCheck extends KeyCheckWorker {
/** @var SettingsController */ /** @var SettingsController */
private $settings; private $settings;
function __construct(SettingsController $settings, $timer = false) { function __construct(SettingsController $settings) {
$this->settings = $settings; $this->settings = $settings;
parent::__construct($timer); parent::__construct();
} }

View File

@ -12,9 +12,9 @@ class SendingServiceKeyCheck extends KeyCheckWorker {
/** @var SettingsController */ /** @var SettingsController */
private $settings; private $settings;
function __construct(SettingsController $settings, $timer = false) { function __construct(SettingsController $settings) {
$this->settings = $settings; $this->settings = $settings;
parent::__construct($timer); parent::__construct();
} }
function checkProcessingRequirements() { function checkProcessingRequirements() {

View File

@ -20,8 +20,6 @@ use MailPoetVendor\Monolog\Logger;
class Scheduler { class Scheduler {
const TASK_BATCH_SIZE = 5; const TASK_BATCH_SIZE = 5;
public $timer;
/** @var SubscribersFinder */ /** @var SubscribersFinder */
private $subscribers_finder; private $subscribers_finder;
@ -34,18 +32,19 @@ class Scheduler {
function __construct( function __construct(
SubscribersFinder $subscribers_finder, SubscribersFinder $subscribers_finder,
LoggerFactory $logger_factory, LoggerFactory $logger_factory,
CronHelper $cron_helper, CronHelper $cron_helper
$timer = false
) { ) {
$this->timer = ($timer) ? $timer : microtime(true);
// abort if execution limit is reached
$this->cron_helper = $cron_helper; $this->cron_helper = $cron_helper;
$this->cron_helper->enforceExecutionLimit($this->timer);
$this->subscribers_finder = $subscribers_finder; $this->subscribers_finder = $subscribers_finder;
$this->logger_factory = $logger_factory; $this->logger_factory = $logger_factory;
} }
function process() { function process($timer = false) {
$timer = $timer ?: microtime(true);
// abort if execution limit is reached
$this->cron_helper->enforceExecutionLimit($timer);
$scheduled_queues = self::getScheduledQueues(); $scheduled_queues = self::getScheduledQueues();
if (!count($scheduled_queues)) return false; if (!count($scheduled_queues)) return false;
$this->updateTasks($scheduled_queues); $this->updateTasks($scheduled_queues);
@ -64,7 +63,7 @@ class Scheduler {
} elseif ($newsletter->type === Newsletter::TYPE_AUTOMATIC) { } elseif ($newsletter->type === Newsletter::TYPE_AUTOMATIC) {
$this->processScheduledAutomaticEmail($newsletter, $queue); $this->processScheduledAutomaticEmail($newsletter, $queue);
} }
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
} }
} }

View File

@ -21,7 +21,7 @@ class Migration extends SimpleWorker {
return empty($completed_tasks); return empty($completed_tasks);
} }
function prepareTaskStrategy(ScheduledTask $task) { function prepareTaskStrategy(ScheduledTask $task, $timer) {
$unmigrated_columns = $this->checkUnmigratedColumnsExist(); $unmigrated_columns = $this->checkUnmigratedColumnsExist();
$unmigrated_queues_count = 0; $unmigrated_queues_count = 0;
$unmigrated_queue_subscribers = []; $unmigrated_queue_subscribers = [];
@ -73,9 +73,9 @@ class Migration extends SimpleWorker {
} }
} }
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
$this->migrateSendingQueues(); $this->migrateSendingQueues($timer);
$this->migrateSubscribers(); $this->migrateSubscribers($timer);
$this->resumeSending(); $this->resumeSending();
return true; return true;
} }
@ -108,7 +108,7 @@ class Migration extends SimpleWorker {
/* /*
* Migrate all sending queues without converting subscriber data * Migrate all sending queues without converting subscriber data
*/ */
function migrateSendingQueues() { function migrateSendingQueues($timer) {
global $wpdb; global $wpdb;
$queues = $this->getUnmigratedQueues() $queues = $this->getUnmigratedQueues()
@ -128,7 +128,7 @@ class Migration extends SimpleWorker {
if (!empty($queues)) { if (!empty($queues)) {
foreach (array_chunk($queues, self::BATCH_SIZE) as $queue_batch) { foreach (array_chunk($queues, self::BATCH_SIZE) as $queue_batch) {
// abort if execution limit is reached // abort if execution limit is reached
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
foreach ($queue_batch as $queue) { foreach ($queue_batch as $queue) {
// create a new scheduled task of type "sending" // create a new scheduled task of type "sending"
@ -158,7 +158,7 @@ class Migration extends SimpleWorker {
/* /*
* Migrate subscribers for in-progress sending tasks from the `subscribers` field to a separate table * Migrate subscribers for in-progress sending tasks from the `subscribers` field to a separate table
*/ */
function migrateSubscribers() { function migrateSubscribers($timer) {
global $wpdb; global $wpdb;
// find in-progress queues that have serialized subscribers // find in-progress queues that have serialized subscribers
@ -177,16 +177,16 @@ class Migration extends SimpleWorker {
if (!empty($task_ids)) { if (!empty($task_ids)) {
foreach ($task_ids as $task_id) { foreach ($task_ids as $task_id) {
// abort if execution limit is reached // abort if execution limit is reached
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
$this->migrateTaskSubscribers($task_id); $this->migrateTaskSubscribers($task_id, $timer);
} }
} }
return true; return true;
} }
function migrateTaskSubscribers($task_id) { function migrateTaskSubscribers($task_id, $timer) {
global $wpdb; global $wpdb;
$migrated_unprocessed_count = ScheduledTaskSubscriber::getUnprocessedCount($task_id); $migrated_unprocessed_count = ScheduledTaskSubscriber::getUnprocessedCount($task_id);
@ -212,7 +212,7 @@ class Migration extends SimpleWorker {
$subscribers_to_migrate = array_slice($subscribers['to_process'], $migrated_unprocessed_count); $subscribers_to_migrate = array_slice($subscribers['to_process'], $migrated_unprocessed_count);
foreach ($subscribers_to_migrate as $sub_id) { foreach ($subscribers_to_migrate as $sub_id) {
// abort if execution limit is reached // abort if execution limit is reached
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
ScheduledTaskSubscriber::createOrUpdate([ ScheduledTaskSubscriber::createOrUpdate([
'task_id' => $task_id, 'task_id' => $task_id,
@ -226,7 +226,7 @@ class Migration extends SimpleWorker {
$subscribers_to_migrate = array_slice($subscribers['processed'], $migrated_processed_count); $subscribers_to_migrate = array_slice($subscribers['processed'], $migrated_processed_count);
foreach ($subscribers_to_migrate as $sub_id) { foreach ($subscribers_to_migrate as $sub_id) {
// abort if execution limit is reached // abort if execution limit is reached
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
ScheduledTaskSubscriber::createOrUpdate([ ScheduledTaskSubscriber::createOrUpdate([
'task_id' => $task_id, 'task_id' => $task_id,

View File

@ -25,7 +25,6 @@ use function MailPoet\Util\array_column;
class SendingQueue { class SendingQueue {
public $mailer_task; public $mailer_task;
public $newsletter_task; public $newsletter_task;
public $timer;
public $batch_size; public $batch_size;
const BATCH_SIZE = 20; const BATCH_SIZE = 20;
const TASK_BATCH_SIZE = 5; const TASK_BATCH_SIZE = 5;
@ -54,7 +53,6 @@ class SendingQueue {
LoggerFactory $logger_factory, LoggerFactory $logger_factory,
NewslettersRepository $newsletters_repository, NewslettersRepository $newsletters_repository,
CronHelper $cron_helper, CronHelper $cron_helper,
$timer = false,
$mailer_task = false, $mailer_task = false,
$newsletter_task = false $newsletter_task = false
) { ) {
@ -62,7 +60,6 @@ class SendingQueue {
$this->stats_notifications_scheduler = $stats_notifications_scheduler; $this->stats_notifications_scheduler = $stats_notifications_scheduler;
$this->mailer_task = ($mailer_task) ? $mailer_task : new MailerTask(); $this->mailer_task = ($mailer_task) ? $mailer_task : new MailerTask();
$this->newsletter_task = ($newsletter_task) ? $newsletter_task : new NewsletterTask(); $this->newsletter_task = ($newsletter_task) ? $newsletter_task : new NewsletterTask();
$this->timer = ($timer) ? $timer : microtime(true);
$this->mailerMetaInfo = new MetaInfo; $this->mailerMetaInfo = new MetaInfo;
$wp = new WPFunctions; $wp = new WPFunctions;
$this->batch_size = $wp->applyFilters('mailpoet_cron_worker_sending_queue_batch_size', self::BATCH_SIZE); $this->batch_size = $wp->applyFilters('mailpoet_cron_worker_sending_queue_batch_size', self::BATCH_SIZE);
@ -71,8 +68,9 @@ class SendingQueue {
$this->cron_helper = $cron_helper; $this->cron_helper = $cron_helper;
} }
function process() { function process($timer = false) {
$this->enforceSendingAndExecutionLimits(); $timer = $timer ?: microtime(true);
$this->enforceSendingAndExecutionLimits($timer);
foreach (self::getRunningQueues() as $queue) { foreach (self::getRunningQueues() as $queue) {
if (!$queue instanceof SendingTask) continue; if (!$queue instanceof SendingTask) continue;
ScheduledTaskModel::touchAllByIds([$queue->task_id]); ScheduledTaskModel::touchAllByIds([$queue->task_id]);
@ -147,7 +145,8 @@ class SendingQueue {
$queue = $this->processQueue( $queue = $this->processQueue(
$queue, $queue,
$_newsletter, $_newsletter,
$found_subscribers $found_subscribers,
$timer
); );
$this->logger_factory->getLogger(LoggerFactory::TOPIC_NEWSLETTERS)->addInfo( $this->logger_factory->getLogger(LoggerFactory::TOPIC_NEWSLETTERS)->addInfo(
'after queue chunk processing', 'after queue chunk processing',
@ -161,12 +160,12 @@ class SendingQueue {
$this->newsletter_task->markNewsletterAsSent($newsletter, $queue); $this->newsletter_task->markNewsletterAsSent($newsletter, $queue);
$this->stats_notifications_scheduler->schedule($this->newsletters_repository->findOneById($newsletter->id)); $this->stats_notifications_scheduler->schedule($this->newsletters_repository->findOneById($newsletter->id));
} }
$this->enforceSendingAndExecutionLimits(); $this->enforceSendingAndExecutionLimits($timer);
} }
} }
} }
function processQueue($queue, $newsletter, $subscribers) { function processQueue($queue, $newsletter, $subscribers, $timer) {
// determine if processing is done in bulk or individually // determine if processing is done in bulk or individually
$processing_method = $this->mailer_task->getProcessingMethod(); $processing_method = $this->mailer_task->getProcessingMethod();
$prepared_newsletters = []; $prepared_newsletters = [];
@ -204,6 +203,7 @@ class SendingQueue {
$prepared_newsletters[0], $prepared_newsletters[0],
$prepared_subscribers[0], $prepared_subscribers[0],
$statistics[0], $statistics[0],
$timer,
['unsubscribe_url' => $unsubscribe_urls[0], 'meta' => $metas[0]] ['unsubscribe_url' => $unsubscribe_urls[0], 'meta' => $metas[0]]
); );
$prepared_newsletters = []; $prepared_newsletters = [];
@ -220,6 +220,7 @@ class SendingQueue {
$prepared_newsletters, $prepared_newsletters,
$prepared_subscribers, $prepared_subscribers,
$statistics, $statistics,
$timer,
['unsubscribe_url' => $unsubscribe_urls, 'meta' => $metas] ['unsubscribe_url' => $unsubscribe_urls, 'meta' => $metas]
); );
} }
@ -228,7 +229,7 @@ class SendingQueue {
function sendNewsletter( function sendNewsletter(
SendingTask $sending_task, $prepared_subscriber_id, $prepared_newsletter, SendingTask $sending_task, $prepared_subscriber_id, $prepared_newsletter,
$prepared_subscriber, $statistics, $extra_params = [] $prepared_subscriber, $statistics, $timer, $extra_params = []
) { ) {
// send newsletter // send newsletter
$send_result = $this->mailer_task->send( $send_result = $this->mailer_task->send(
@ -241,13 +242,14 @@ class SendingQueue {
$send_result, $send_result,
[$prepared_subscriber], [$prepared_subscriber],
[$prepared_subscriber_id], [$prepared_subscriber_id],
[$statistics] [$statistics],
$timer
); );
} }
function sendNewsletters( function sendNewsletters(
SendingTask $sending_task, $prepared_subscribers_ids, $prepared_newsletters, SendingTask $sending_task, $prepared_subscribers_ids, $prepared_newsletters,
$prepared_subscribers, $statistics, $extra_params = [] $prepared_subscribers, $statistics, $timer, $extra_params = []
) { ) {
// send newsletters // send newsletters
$send_result = $this->mailer_task->sendBulk( $send_result = $this->mailer_task->sendBulk(
@ -260,7 +262,8 @@ class SendingQueue {
$send_result, $send_result,
$prepared_subscribers, $prepared_subscribers,
$prepared_subscribers_ids, $prepared_subscribers_ids,
$statistics $statistics,
$timer
); );
} }
@ -269,7 +272,8 @@ class SendingQueue {
$send_result, $send_result,
array $prepared_subscribers, array $prepared_subscribers,
array $prepared_subscribers_ids, array $prepared_subscribers_ids,
array $statistics array $statistics,
$timer
) { ) {
// log error message and schedule retry/pause sending // log error message and schedule retry/pause sending
if ($send_result['response'] === false) { if ($send_result['response'] === false) {
@ -292,14 +296,14 @@ class SendingQueue {
$this->mailer_task->updateSentCount(); $this->mailer_task->updateSentCount();
// enforce execution limits if queue is still being processed // enforce execution limits if queue is still being processed
if ($sending_task->status !== ScheduledTaskModel::STATUS_COMPLETED) { if ($sending_task->status !== ScheduledTaskModel::STATUS_COMPLETED) {
$this->enforceSendingAndExecutionLimits(); $this->enforceSendingAndExecutionLimits($timer);
} }
return $sending_task; return $sending_task;
} }
function enforceSendingAndExecutionLimits() { function enforceSendingAndExecutionLimits($timer) {
// abort if execution limit is reached // abort if execution limit is reached
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
// abort if sending limit has been reached // abort if sending limit has been reached
MailerLog::enforceExecutionRequirements(); MailerLog::enforceExecutionRequirements();
} }

View File

@ -10,7 +10,6 @@ use MailPoet\Models\ScheduledTask;
use MailPoet\WP\Functions as WPFunctions; use MailPoet\WP\Functions as WPFunctions;
abstract class SimpleWorker { abstract class SimpleWorker {
public $timer;
private $wp; private $wp;
const TASK_TYPE = null; const TASK_TYPE = null;
const TASK_BATCH_SIZE = 5; const TASK_BATCH_SIZE = 5;
@ -26,15 +25,13 @@ abstract class SimpleWorker {
/** @var CronWorkerScheduler */ /** @var CronWorkerScheduler */
protected $cron_worker_scheduler; protected $cron_worker_scheduler;
function __construct($timer = false) { function __construct() {
if (static::TASK_TYPE === null) { if (static::TASK_TYPE === null) {
throw new \Exception('Constant TASK_TYPE is not defined on subclass ' . get_class($this)); throw new \Exception('Constant TASK_TYPE is not defined on subclass ' . get_class($this));
} }
$this->timer = ($timer) ? $timer : microtime(true);
// abort if execution limit is reached
$this->cron_helper = ContainerWrapper::getInstance()->get(CronHelper::class);
$this->cron_helper->enforceExecutionLimit($this->timer);
$this->wp = new WPFunctions(); $this->wp = new WPFunctions();
$this->cron_helper = ContainerWrapper::getInstance()->get(CronHelper::class);
$this->cron_worker_scheduler = ContainerWrapper::getInstance()->get(CronWorkerScheduler::class); $this->cron_worker_scheduler = ContainerWrapper::getInstance()->get(CronWorkerScheduler::class);
} }
@ -45,7 +42,12 @@ abstract class SimpleWorker {
function init() { function init() {
} }
function process() { function process($timer = false) {
$timer = $timer ?: microtime(true);
// abort if execution limit is reached
$this->cron_helper->enforceExecutionLimit($timer);
if (!$this->checkProcessingRequirements()) { if (!$this->checkProcessingRequirements()) {
return false; return false;
} }
@ -65,10 +67,10 @@ abstract class SimpleWorker {
$task = null; $task = null;
try { try {
foreach ($scheduled_tasks as $i => $task) { foreach ($scheduled_tasks as $i => $task) {
$this->prepareTask($task); $this->prepareTask($task, $timer);
} }
foreach ($running_tasks as $i => $task) { foreach ($running_tasks as $i => $task) {
$this->processTask($task); $this->processTask($task, $timer);
} }
} catch (\Exception $e) { } catch (\Exception $e) {
if ($task && $e->getCode() !== CronHelper::DAEMON_EXECUTION_LIMIT_REACHED) { if ($task && $e->getCode() !== CronHelper::DAEMON_EXECUTION_LIMIT_REACHED) {
@ -84,20 +86,20 @@ abstract class SimpleWorker {
$this->cron_worker_scheduler->schedule(static::TASK_TYPE, static::getNextRunDate()); $this->cron_worker_scheduler->schedule(static::TASK_TYPE, static::getNextRunDate());
} }
function prepareTask(ScheduledTask $task) { function prepareTask(ScheduledTask $task, $timer) {
// abort if execution limit is reached // abort if execution limit is reached
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
$prepare_completed = $this->prepareTaskStrategy($task); $prepare_completed = $this->prepareTaskStrategy($task, $timer);
if ($prepare_completed) { if ($prepare_completed) {
$task->status = null; $task->status = null;
$task->save(); $task->save();
} }
} }
function processTask(ScheduledTask $task) { function processTask(ScheduledTask $task, $timer) {
// abort if execution limit is reached // abort if execution limit is reached
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
if (!static::SUPPORT_MULTIPLE_INSTANCES) { if (!static::SUPPORT_MULTIPLE_INSTANCES) {
if ($this->rescheduleOutdated($task)) { if ($this->rescheduleOutdated($task)) {
@ -111,7 +113,7 @@ abstract class SimpleWorker {
$this->startProgress($task); $this->startProgress($task);
try { try {
$completed = $this->processTaskStrategy($task); $completed = $this->processTaskStrategy($task, $timer);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->stopProgress($task); $this->stopProgress($task);
throw $e; throw $e;
@ -126,11 +128,11 @@ abstract class SimpleWorker {
return (bool)$completed; return (bool)$completed;
} }
function prepareTaskStrategy(ScheduledTask $task) { function prepareTaskStrategy(ScheduledTask $task, $timer) {
return true; return true;
} }
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
return true; return true;
} }

View File

@ -31,9 +31,6 @@ class AutomatedEmails extends SimpleWorker {
/** @var MetaInfo */ /** @var MetaInfo */
private $mailerMetaInfo; private $mailerMetaInfo;
/** @var float */
public $timer;
/** @var NewslettersRepository */ /** @var NewslettersRepository */
private $repository; private $repository;
@ -46,15 +43,13 @@ class AutomatedEmails extends SimpleWorker {
SettingsController $settings, SettingsController $settings,
NewslettersRepository $repository, NewslettersRepository $repository,
NewsletterStatisticsRepository $newsletter_statistics_repository, NewsletterStatisticsRepository $newsletter_statistics_repository,
MetaInfo $mailerMetaInfo, MetaInfo $mailerMetaInfo
$timer = false
) { ) {
parent::__construct($timer); parent::__construct();
$this->mailer = $mailer; $this->mailer = $mailer;
$this->settings = $settings; $this->settings = $settings;
$this->renderer = $renderer; $this->renderer = $renderer;
$this->mailerMetaInfo = $mailerMetaInfo; $this->mailerMetaInfo = $mailerMetaInfo;
$this->timer = $timer ?: microtime(true);
$this->repository = $repository; $this->repository = $repository;
$this->newsletter_statistics_repository = $newsletter_statistics_repository; $this->newsletter_statistics_repository = $newsletter_statistics_repository;
} }
@ -79,7 +74,7 @@ class AutomatedEmails extends SimpleWorker {
return (bool)$settings['automated']; return (bool)$settings['automated'];
} }
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
try { try {
$settings = $this->settings->get(Worker::SETTINGS_KEY); $settings = $this->settings->get(Worker::SETTINGS_KEY);
$newsletters = $this->getNewsletters(); $newsletters = $this->getNewsletters();

View File

@ -24,9 +24,6 @@ class Worker {
const TASK_TYPE = 'stats_notification'; const TASK_TYPE = 'stats_notification';
const SETTINGS_KEY = 'stats_notifications'; const SETTINGS_KEY = 'stats_notifications';
/** @var float */
public $timer;
/** @var Renderer */ /** @var Renderer */
private $renderer; private $renderer;
@ -63,10 +60,8 @@ class Worker {
StatsNotificationsRepository $repository, StatsNotificationsRepository $repository,
NewsletterLinkRepository $newsletter_link_repository, NewsletterLinkRepository $newsletter_link_repository,
NewsletterStatisticsRepository $newsletter_statistics_repository, NewsletterStatisticsRepository $newsletter_statistics_repository,
EntityManager $entity_manager, EntityManager $entity_manager
$timer = false
) { ) {
$this->timer = $timer ?: microtime(true);
$this->renderer = $renderer; $this->renderer = $renderer;
$this->mailer = $mailer; $this->mailer = $mailer;
$this->settings = $settings; $this->settings = $settings;
@ -79,7 +74,8 @@ class Worker {
} }
/** @throws \Exception */ /** @throws \Exception */
function process() { function process($timer = false) {
$timer = $timer ?: microtime(true);
$settings = $this->settings->get(self::SETTINGS_KEY); $settings = $this->settings->get(self::SETTINGS_KEY);
foreach ($this->repository->findScheduled(Sending::RESULT_BATCH_SIZE) as $stats_notification_entity) { foreach ($this->repository->findScheduled(Sending::RESULT_BATCH_SIZE) as $stats_notification_entity) {
try { try {
@ -94,7 +90,7 @@ class Worker {
} finally { } finally {
$this->markTaskAsFinished($stats_notification_entity->getTask()); $this->markTaskAsFinished($stats_notification_entity->getTask());
} }
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
} }
} }

View File

@ -14,7 +14,7 @@ class SubscriberLinkTokens extends SimpleWorker {
const BATCH_SIZE = 10000; const BATCH_SIZE = 10000;
const AUTOMATIC_SCHEDULING = false; const AUTOMATIC_SCHEDULING = false;
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
$count = Subscriber::whereNull('link_token')->count(); $count = Subscriber::whereNull('link_token')->count();
if ($count) { if ($count) {
$auth_key = defined('AUTH_KEY') ? AUTH_KEY : ''; $auth_key = defined('AUTH_KEY') ? AUTH_KEY : '';

View File

@ -15,16 +15,16 @@ class UnsubscribeTokens extends SimpleWorker {
const BATCH_SIZE = 1000; const BATCH_SIZE = 1000;
const AUTOMATIC_SCHEDULING = false; const AUTOMATIC_SCHEDULING = false;
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
$meta = $task->getMeta(); $meta = $task->getMeta();
do { do {
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
$subscribers_count = $this->addTokens(Subscriber::class, $meta['last_subscriber_id']); $subscribers_count = $this->addTokens(Subscriber::class, $meta['last_subscriber_id']);
$task->meta = $meta; $task->meta = $meta;
$task->save(); $task->save();
} while ($subscribers_count === self::BATCH_SIZE); } while ($subscribers_count === self::BATCH_SIZE);
do { do {
$this->cron_helper->enforceExecutionLimit($this->timer); $this->cron_helper->enforceExecutionLimit($timer);
$newsletters_count = $this->addTokens(Newsletter::class, $meta['last_newsletter_id']); $newsletters_count = $this->addTokens(Newsletter::class, $meta['last_newsletter_id']);
$task->meta = $meta; $task->meta = $meta;
$task->save(); $task->save();

View File

@ -22,19 +22,18 @@ class WooCommercePastOrders extends SimpleWorker {
function __construct( function __construct(
WCHelper $woocommerce_helper, WCHelper $woocommerce_helper,
WooCommercePurchases $woocommerce_purchases, WooCommercePurchases $woocommerce_purchases
$timer = false
) { ) {
$this->woocommerce_helper = $woocommerce_helper; $this->woocommerce_helper = $woocommerce_helper;
$this->woocommerce_purchases = $woocommerce_purchases; $this->woocommerce_purchases = $woocommerce_purchases;
parent::__construct($timer); parent::__construct();
} }
function checkProcessingRequirements() { function checkProcessingRequirements() {
return $this->woocommerce_helper->isWooCommerceActive() && empty($this->getCompletedTasks()); // run only once return $this->woocommerce_helper->isWooCommerceActive() && empty($this->getCompletedTasks()); // run only once
} }
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
$oldest_click = StatisticsClicks::orderByAsc('created_at')->limit(1)->findOne(); $oldest_click = StatisticsClicks::orderByAsc('created_at')->limit(1)->findOne();
if (!$oldest_click instanceof StatisticsClicks) { if (!$oldest_click instanceof StatisticsClicks) {
return true; return true;

View File

@ -18,17 +18,17 @@ class WooCommerceSync extends SimpleWorker {
/** @var WooCommerceHelper */ /** @var WooCommerceHelper */
private $woocommerce_helper; private $woocommerce_helper;
function __construct(WooCommerceSegment $woocommerce_segment, WooCommerceHelper $woocommerce_helper, $timer = false) { function __construct(WooCommerceSegment $woocommerce_segment, WooCommerceHelper $woocommerce_helper) {
$this->woocommerce_segment = $woocommerce_segment; $this->woocommerce_segment = $woocommerce_segment;
$this->woocommerce_helper = $woocommerce_helper; $this->woocommerce_helper = $woocommerce_helper;
parent::__construct($timer); parent::__construct();
} }
function checkProcessingRequirements() { function checkProcessingRequirements() {
return $this->woocommerce_helper->isWooCommerceActive(); return $this->woocommerce_helper->isWooCommerceActive();
} }
function processTaskStrategy(ScheduledTask $task) { function processTaskStrategy(ScheduledTask $task, $timer) {
$this->woocommerce_segment->synchronizeCustomers(); $this->woocommerce_segment->synchronizeCustomers();
return true; return true;
} }

View File

@ -136,24 +136,23 @@ class WorkersFactory {
} }
/** @return SchedulerWorker */ /** @return SchedulerWorker */
function createScheduleWorker($timer) { function createScheduleWorker() {
return new SchedulerWorker($this->subscribers_finder, $this->logger_factory, $this->cron_helper, $timer); return new SchedulerWorker($this->subscribers_finder, $this->logger_factory, $this->cron_helper);
} }
/** @return SendingQueueWorker */ /** @return SendingQueueWorker */
function createQueueWorker($timer) { function createQueueWorker() {
return new SendingQueueWorker( return new SendingQueueWorker(
$this->sending_error_handler, $this->sending_error_handler,
$this->statsNotificationsScheduler, $this->statsNotificationsScheduler,
$this->logger_factory, $this->logger_factory,
$this->newsletters_repository, $this->newsletters_repository,
$this->cron_helper, $this->cron_helper
$timer
); );
} }
/** @return StatsNotificationsWorker */ /** @return StatsNotificationsWorker */
function createStatsNotificationsWorker($timer) { function createStatsNotificationsWorker() {
return new StatsNotificationsWorker( return new StatsNotificationsWorker(
$this->mailer, $this->mailer,
$this->renderer, $this->renderer,
@ -163,81 +162,79 @@ class WorkersFactory {
$this->stats_notifications_repository, $this->stats_notifications_repository,
$this->newsletter_link_repository, $this->newsletter_link_repository,
$this->newsletter_statistics_repository, $this->newsletter_statistics_repository,
$this->entity_manager, $this->entity_manager
$timer
); );
} }
/** @return StatsNotificationsWorkerForAutomatedEmails */ /** @return StatsNotificationsWorkerForAutomatedEmails */
function createStatsNotificationsWorkerForAutomatedEmails($timer) { function createStatsNotificationsWorkerForAutomatedEmails() {
return new StatsNotificationsWorkerForAutomatedEmails( return new StatsNotificationsWorkerForAutomatedEmails(
$this->mailer, $this->mailer,
$this->renderer, $this->renderer,
$this->settings, $this->settings,
$this->newsletters_repository, $this->newsletters_repository,
$this->newsletter_statistics_repository, $this->newsletter_statistics_repository,
$this->mailerMetaInfo, $this->mailerMetaInfo
$timer
); );
} }
/** @return SendingServiceKeyCheckWorker */ /** @return SendingServiceKeyCheckWorker */
function createSendingServiceKeyCheckWorker($timer) { function createSendingServiceKeyCheckWorker() {
return new SendingServiceKeyCheckWorker($this->settings, $timer); return new SendingServiceKeyCheckWorker($this->settings);
} }
/** @return PremiumKeyCheckWorker */ /** @return PremiumKeyCheckWorker */
function createPremiumKeyCheckWorker($timer) { function createPremiumKeyCheckWorker() {
return new PremiumKeyCheckWorker($this->settings, $timer); return new PremiumKeyCheckWorker($this->settings);
} }
/** @return BounceWorker */ /** @return BounceWorker */
function createBounceWorker($timer) { function createBounceWorker() {
return new BounceWorker($this->settings, $timer); return new BounceWorker($this->settings);
} }
/** @return MigrationWorker */ /** @return MigrationWorker */
function createMigrationWorker($timer) { function createMigrationWorker() {
return new MigrationWorker($timer); return new MigrationWorker();
} }
/** @return WooCommerceSyncWorker */ /** @return WooCommerceSyncWorker */
function createWooCommerceSyncWorker($timer) { function createWooCommerceSyncWorker() {
return new WooCommerceSyncWorker($this->woocommerce_segment, $this->woocommerce_helper, $timer); return new WooCommerceSyncWorker($this->woocommerce_segment, $this->woocommerce_helper);
} }
/** @return ExportFilesCleanup */ /** @return ExportFilesCleanup */
function createExportFilesCleanupWorker($timer) { function createExportFilesCleanupWorker() {
return new ExportFilesCleanup($timer); return new ExportFilesCleanup();
} }
/** @return Beamer */ /** @return Beamer */
function createBeamerkWorker($timer) { function createBeamerkWorker() {
return new Beamer($this->settings, WPFunctions::get(), $timer); return new Beamer($this->settings, WPFunctions::get());
} }
/** @return InactiveSubscribers */ /** @return InactiveSubscribers */
function createInactiveSubscribersWorker($timer) { function createInactiveSubscribersWorker() {
return new InactiveSubscribers($this->inactive_subscribers_controller, $this->settings, $timer); return new InactiveSubscribers($this->inactive_subscribers_controller, $this->settings);
} }
/** @return UnsubscribeTokens */ /** @return UnsubscribeTokens */
function createUnsubscribeTokensWorker($timer) { function createUnsubscribeTokensWorker() {
return new UnsubscribeTokens($timer); return new UnsubscribeTokens();
} }
/** @return SubscriberLinkTokens */ /** @return SubscriberLinkTokens */
function createSubscriberLinkTokensWorker($timer) { function createSubscriberLinkTokensWorker() {
return new SubscriberLinkTokens($timer); return new SubscriberLinkTokens();
} }
/** @return AuthorizedSendingEmailsCheck */ /** @return AuthorizedSendingEmailsCheck */
function createAuthorizedSendingEmailsCheckWorker($timer) { function createAuthorizedSendingEmailsCheckWorker() {
return new AuthorizedSendingEmailsCheck($this->authorized_emails_controller, $timer); return new AuthorizedSendingEmailsCheck($this->authorized_emails_controller);
} }
/** @return WooCommercePastOrders */ /** @return WooCommercePastOrders */
function createWooCommercePastOrdersWorker($timer) { function createWooCommercePastOrdersWorker() {
return new WooCommercePastOrders($this->woocommerce_helper, $this->woocommerce_purchases, $timer); return new WooCommercePastOrders($this->woocommerce_helper, $this->woocommerce_purchases);
} }
} }

View File

@ -22,7 +22,7 @@ class AuthorizedSendingEmailsCheckTest extends \MailPoetTest {
function testItRunsCheckOnBridge() { function testItRunsCheckOnBridge() {
$bridge_mock = $this->makeEmpty(AuthorizedEmailsController::class, ['checkAuthorizedEmailAddresses' => Stub\Expected::once()]); $bridge_mock = $this->makeEmpty(AuthorizedEmailsController::class, ['checkAuthorizedEmailAddresses' => Stub\Expected::once()]);
$worker = new AuthorizedSendingEmailsCheck($bridge_mock); $worker = new AuthorizedSendingEmailsCheck($bridge_mock);
$worker->processTaskStrategy(ScheduledTask::createOrUpdate([])); $worker->processTaskStrategy(ScheduledTask::createOrUpdate([]), microtime(true));
} }
function testItDoesNotScheduleAutomatically() { function testItDoesNotScheduleAutomatically() {

View File

@ -56,20 +56,20 @@ class BounceTest extends \MailPoetTest {
function testItDeletesAllSubscribersIfThereAreNoSubscribersToProcessWhenPreparingTask() { function testItDeletesAllSubscribersIfThereAreNoSubscribersToProcessWhenPreparingTask() {
// 1st run - subscribers will be processed // 1st run - subscribers will be processed
$task = $this->createScheduledTask(); $task = $this->createScheduledTask();
$this->worker->prepareTask($task); $this->worker->prepareTask($task, microtime(true));
expect(ScheduledTaskSubscriber::where('task_id', $task->id)->findMany())->notEmpty(); expect(ScheduledTaskSubscriber::where('task_id', $task->id)->findMany())->notEmpty();
// 2nd run - nothing more to process, ScheduledTaskSubscriber will be cleaned up // 2nd run - nothing more to process, ScheduledTaskSubscriber will be cleaned up
Subscriber::deleteMany(); Subscriber::deleteMany();
$task = $this->createScheduledTask(); $task = $this->createScheduledTask();
$this->worker->prepareTask($task); $this->worker->prepareTask($task, microtime(true));
expect(ScheduledTaskSubscriber::where('task_id', $task->id)->findMany())->isEmpty(); expect(ScheduledTaskSubscriber::where('task_id', $task->id)->findMany())->isEmpty();
} }
function testItPreparesTask() { function testItPreparesTask() {
$task = $this->createScheduledTask(); $task = $this->createScheduledTask();
expect(ScheduledTaskSubscriber::getUnprocessedCount($task->id))->isEmpty(); expect(ScheduledTaskSubscriber::getUnprocessedCount($task->id))->isEmpty();
$this->worker->prepareTask($task); $this->worker->prepareTask($task, microtime(true));
expect($task->status)->null(); expect($task->status)->null();
expect(ScheduledTaskSubscriber::getUnprocessedCount($task->id))->notEmpty(); expect(ScheduledTaskSubscriber::getUnprocessedCount($task->id))->notEmpty();
} }
@ -77,21 +77,21 @@ class BounceTest extends \MailPoetTest {
function testItDeletesAllSubscribersIfThereAreNoSubscribersToProcessWhenProcessingTask() { function testItDeletesAllSubscribersIfThereAreNoSubscribersToProcessWhenProcessingTask() {
// prepare subscribers // prepare subscribers
$task = $this->createScheduledTask(); $task = $this->createScheduledTask();
$this->worker->prepareTask($task); $this->worker->prepareTask($task, microtime(true));
expect(ScheduledTaskSubscriber::where('task_id', $task->id)->findMany())->notEmpty(); expect(ScheduledTaskSubscriber::where('task_id', $task->id)->findMany())->notEmpty();
// process - no subscribers found, ScheduledTaskSubscriber will be cleaned up // process - no subscribers found, ScheduledTaskSubscriber will be cleaned up
Subscriber::deleteMany(); Subscriber::deleteMany();
$task = $this->createScheduledTask(); $task = $this->createScheduledTask();
$this->worker->processTask($task); $this->worker->processTask($task, microtime(true));
expect(ScheduledTaskSubscriber::where('task_id', $task->id)->findMany())->isEmpty(); expect(ScheduledTaskSubscriber::where('task_id', $task->id)->findMany())->isEmpty();
} }
function testItProcessesTask() { function testItProcessesTask() {
$task = $this->createRunningTask(); $task = $this->createRunningTask();
$this->worker->prepareTask($task); $this->worker->prepareTask($task, microtime(true));
expect(ScheduledTaskSubscriber::getUnprocessedCount($task->id))->notEmpty(); expect(ScheduledTaskSubscriber::getUnprocessedCount($task->id))->notEmpty();
$this->worker->processTask($task); $this->worker->processTask($task, microtime(true));
expect(ScheduledTaskSubscriber::getProcessedCount($task->id))->notEmpty(); expect(ScheduledTaskSubscriber::getProcessedCount($task->id))->notEmpty();
} }

View File

@ -15,7 +15,7 @@ class ExportFilesCleanupTest extends \MailPoetTest {
touch($new_file_path); touch($new_file_path);
$cleanup = new ExportFilesCleanup(); $cleanup = new ExportFilesCleanup();
$cleanup->processTaskStrategy(ScheduledTask::createOrUpdate([])); $cleanup->processTaskStrategy(ScheduledTask::createOrUpdate([]), microtime(true));
$this->assertFileExists($new_file_path); $this->assertFileExists($new_file_path);
$this->assertFileNotExists($old_file_path); $this->assertFileNotExists($old_file_path);

View File

@ -33,7 +33,7 @@ class InactiveSubscribersTest extends \MailPoetTest {
], $this); ], $this);
$worker = new InactiveSubscribers($controller_mock, $this->settings); $worker = new InactiveSubscribers($controller_mock, $this->settings);
$worker->processTaskStrategy(ScheduledTask::createOrUpdate([])); $worker->processTaskStrategy(ScheduledTask::createOrUpdate([]), microtime(true));
$task = ScheduledTask::where('type', InactiveSubscribers::TASK_TYPE) $task = ScheduledTask::where('type', InactiveSubscribers::TASK_TYPE)
->where('status', ScheduledTask::STATUS_SCHEDULED) ->where('status', ScheduledTask::STATUS_SCHEDULED)
@ -53,7 +53,7 @@ class InactiveSubscribersTest extends \MailPoetTest {
], $this); ], $this);
$worker = new InactiveSubscribers($controller_mock, $this->settings); $worker = new InactiveSubscribers($controller_mock, $this->settings);
$worker->processTaskStrategy(ScheduledTask::createOrUpdate([])); $worker->processTaskStrategy(ScheduledTask::createOrUpdate([]), microtime(true));
} }
function testItSchedulesNextRunWhenFinished() { function testItSchedulesNextRunWhenFinished() {
@ -65,7 +65,7 @@ class InactiveSubscribersTest extends \MailPoetTest {
], $this); ], $this);
$worker = new InactiveSubscribers($controller_mock, $this->settings); $worker = new InactiveSubscribers($controller_mock, $this->settings);
$worker->processTaskStrategy(ScheduledTask::createOrUpdate([])); $worker->processTaskStrategy(ScheduledTask::createOrUpdate([]), microtime(true));
$task = ScheduledTask::where('type', InactiveSubscribers::TASK_TYPE) $task = ScheduledTask::where('type', InactiveSubscribers::TASK_TYPE)
->where('status', ScheduledTask::STATUS_SCHEDULED) ->where('status', ScheduledTask::STATUS_SCHEDULED)
@ -86,7 +86,7 @@ class InactiveSubscribersTest extends \MailPoetTest {
$worker = new InactiveSubscribers($controller_mock, $this->settings); $worker = new InactiveSubscribers($controller_mock, $this->settings);
$worker->processTaskStrategy(ScheduledTask::createOrUpdate( $worker->processTaskStrategy(ScheduledTask::createOrUpdate(
['meta' => ['max_subscriber_id' => 2001 /* 3 iterations of BATCH_SIZE in markInactiveSubscribers */]] ['meta' => ['max_subscriber_id' => 2001 /* 3 iterations of BATCH_SIZE in markInactiveSubscribers */]]
)); ), microtime(true));
expect($controller_mock->markInactiveSubscribers(5, 1000))->equals('ok'); expect($controller_mock->markInactiveSubscribers(5, 1000))->equals('ok');
expect($controller_mock->markActiveSubscribers(5, 1000))->equals('ok'); expect($controller_mock->markActiveSubscribers(5, 1000))->equals('ok');
@ -103,7 +103,7 @@ class InactiveSubscribersTest extends \MailPoetTest {
$task = ScheduledTask::createOrUpdate([]); $task = ScheduledTask::createOrUpdate([]);
$worker = new InactiveSubscribers($controller_mock, $this->settings); $worker = new InactiveSubscribers($controller_mock, $this->settings);
$worker->processTaskStrategy($task); $worker->processTaskStrategy($task, microtime(true));
$meta = $task->getMeta(); $meta = $task->getMeta();
expect(isset($meta['last_subscriber_id']))->equals(false); expect(isset($meta['last_subscriber_id']))->equals(false);
@ -117,9 +117,8 @@ class InactiveSubscribersTest extends \MailPoetTest {
'reactivateInactiveSubscribers' => Stub\Expected::never(), 'reactivateInactiveSubscribers' => Stub\Expected::never(),
], $this); ], $this);
$worker = new InactiveSubscribers($controller_mock, $this->settings, microtime(true) - ($this->cron_helper->getDaemonExecutionLimit() - 1)); $worker = new InactiveSubscribers($controller_mock, $this->settings);
sleep(1);
$this->setExpectedException(\Exception::class, 'Maximum execution time has been reached.'); $this->setExpectedException(\Exception::class, 'Maximum execution time has been reached.');
$worker->processTaskStrategy(ScheduledTask::createOrUpdate([])); $worker->processTaskStrategy(ScheduledTask::createOrUpdate([]), microtime(true) - $this->cron_helper->getDaemonExecutionLimit());
} }
} }

View File

@ -25,7 +25,7 @@ class KeyCheckWorkerTest extends \MailPoetTest {
function testItReturnsTrueOnSuccessfulKeyCheck() { function testItReturnsTrueOnSuccessfulKeyCheck() {
$task = $this->createRunningTask(); $task = $this->createRunningTask();
$result = $this->worker->processTaskStrategy($task); $result = $this->worker->processTaskStrategy($task, microtime(true));
expect($result)->true(); expect($result)->true();
} }
@ -44,7 +44,7 @@ class KeyCheckWorkerTest extends \MailPoetTest {
['rescheduleProgressively' => Expected::once()], ['rescheduleProgressively' => Expected::once()],
$this $this
); );
$result = $worker->processTaskStrategy($task); $result = $worker->processTaskStrategy($task, microtime(true));
expect($result)->false(); expect($result)->false();
} }
@ -61,7 +61,7 @@ class KeyCheckWorkerTest extends \MailPoetTest {
['rescheduleProgressively' => Expected::once()], ['rescheduleProgressively' => Expected::once()],
$this $this
); );
$result = $worker->processTaskStrategy($task); $result = $worker->processTaskStrategy($task, microtime(true));
expect($result)->false(); expect($result)->false();
} }

View File

@ -34,17 +34,10 @@ class SchedulerTest extends \MailPoetTest {
$this->cron_helper = ContainerWrapper::getInstance()->get(CronHelper::class); $this->cron_helper = ContainerWrapper::getInstance()->get(CronHelper::class);
} }
function testItConstructs() {
$scheduler = new Scheduler($this->makeEmpty(SubscribersFinder::class), $this->logger_factory, $this->cron_helper);
expect($scheduler->timer)->greaterOrEquals(5);
$timer = microtime(true) - 2;
$scheduler = new Scheduler($this->makeEmpty(SubscribersFinder::class), $this->logger_factory, $this->cron_helper, $timer);
expect($scheduler->timer)->equals($timer);
}
function testItThrowsExceptionWhenExecutionLimitIsReached() { function testItThrowsExceptionWhenExecutionLimitIsReached() {
try { try {
$scheduler = new Scheduler($this->makeEmpty(SubscribersFinder::class), $this->logger_factory, $this->cron_helper, microtime(true) - $this->cron_helper->getDaemonExecutionLimit()); $scheduler = new Scheduler($this->makeEmpty(SubscribersFinder::class), $this->logger_factory, $this->cron_helper);
$scheduler->process(microtime(true) - $this->cron_helper->getDaemonExecutionLimit());
self::fail('Maximum execution time limit exception was not thrown.'); self::fail('Maximum execution time limit exception was not thrown.');
} catch (\Exception $e) { } catch (\Exception $e) {
expect($e->getMessage())->equals('Maximum execution time has been reached.'); expect($e->getMessage())->equals('Maximum execution time has been reached.');
@ -556,15 +549,11 @@ class SchedulerTest extends \MailPoetTest {
$queue->save(); $queue->save();
$scheduler = Stub::make(Scheduler::class, [ $scheduler = Stub::make(Scheduler::class, [
'processPostNotificationNewsletter' => Expected::exactly(1), 'processPostNotificationNewsletter' => Expected::exactly(1),
'cron_helper' => $this->cron_helper, 'cron_helper' => $this->make(CronHelper::class, [
'enforceExecutionLimit' => Expected::exactly(2), // call at start + during processing
]),
], $this); ], $this);
$scheduler->timer = microtime(true) - $this->cron_helper->getDaemonExecutionLimit(); $scheduler->process();
try {
$scheduler->process();
self::fail('Maximum execution time limit exception was not thrown.');
} catch (\Exception $e) {
expect($e->getMessage())->equals('Maximum execution time has been reached.');
}
} }
function testItDoesNotProcessScheduledJobsWhenNewsletterIsNotActive() { function testItDoesNotProcessScheduledJobsWhenNewsletterIsNotActive() {

View File

@ -56,7 +56,7 @@ class MigrationTest extends \MailPoetTest {
function testItPausesSendingWhenPreparingATask() { function testItPausesSendingWhenPreparingATask() {
$task = $this->createScheduledTask(); $task = $this->createScheduledTask();
expect(MailerLog::isSendingPaused())->false(); expect(MailerLog::isSendingPaused())->false();
$this->worker->prepareTask($task); $this->worker->prepareTask($task, microtime(true));
expect($task->status)->null(); expect($task->status)->null();
expect(MailerLog::isSendingPaused())->true(); expect(MailerLog::isSendingPaused())->true();
} }
@ -66,14 +66,14 @@ class MigrationTest extends \MailPoetTest {
$this->worker->pauseSending(); $this->worker->pauseSending();
expect(MailerLog::isSendingPaused())->true(); expect(MailerLog::isSendingPaused())->true();
$task = $this->createScheduledTask(); $task = $this->createScheduledTask();
$this->worker->prepareTask($task); $this->worker->prepareTask($task, microtime(true));
expect(MailerLog::isSendingPaused())->false(); expect(MailerLog::isSendingPaused())->false();
} }
function testItCompletesTaskIfThereIsNothingToMigrate() { function testItCompletesTaskIfThereIsNothingToMigrate() {
SendingQueue::deleteMany(); SendingQueue::deleteMany();
$task = $this->createScheduledTask(); $task = $this->createScheduledTask();
$this->worker->prepareTask($task); $this->worker->prepareTask($task, microtime(true));
expect(ScheduledTask::findOne($task->id)->status)->equals(ScheduledTask::STATUS_COMPLETED); expect(ScheduledTask::findOne($task->id)->status)->equals(ScheduledTask::STATUS_COMPLETED);
} }
@ -83,7 +83,7 @@ class MigrationTest extends \MailPoetTest {
expect(ScheduledTaskSubscriber::whereGt('task_id', 0)->count())->equals(0); expect(ScheduledTaskSubscriber::whereGt('task_id', 0)->count())->equals(0);
$task = $this->createRunningTask(); $task = $this->createRunningTask();
$this->worker->processTask($task); $this->worker->processTask($task, microtime(true));
expect($this->worker->getUnmigratedQueues()->count())->equals(0); expect($this->worker->getUnmigratedQueues()->count())->equals(0);
expect(ScheduledTask::where('type', SendingTask::TASK_TYPE)->findMany())->count(4); expect(ScheduledTask::where('type', SendingTask::TASK_TYPE)->findMany())->count(4);
@ -105,7 +105,7 @@ class MigrationTest extends \MailPoetTest {
$this->worker->pauseSending(); $this->worker->pauseSending();
expect(MailerLog::isSendingPaused())->true(); expect(MailerLog::isSendingPaused())->true();
$task = $this->createRunningTask(); $task = $this->createRunningTask();
$this->worker->processTask($task); $this->worker->processTask($task, microtime(true));
expect(MailerLog::isSendingPaused())->false(); expect(MailerLog::isSendingPaused())->false();
} }

View File

@ -134,19 +134,6 @@ class SendingQueueTest extends \MailPoetTest {
expect($this->sending_queue_worker->batch_size)->equals(SendingQueueWorker::BATCH_SIZE); expect($this->sending_queue_worker->batch_size)->equals(SendingQueueWorker::BATCH_SIZE);
expect($this->sending_queue_worker->mailer_task instanceof MailerTask); expect($this->sending_queue_worker->mailer_task instanceof MailerTask);
expect($this->sending_queue_worker->newsletter_task instanceof NewsletterTask); expect($this->sending_queue_worker->newsletter_task instanceof NewsletterTask);
expect(strlen($this->sending_queue_worker->timer))->greaterOrEquals(5);
// constructor accepts timer argument
$timer = microtime(true) - 5;
$sending_queue_worker = new SendingQueueWorker(
$this->sending_error_handler,
$this->stats_notifications_worker,
$this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class),
$this->cron_helper,
$timer
);
expect($sending_queue_worker->timer)->equals($timer);
} }
function testItEnforcesExecutionLimitsBeforeQueueProcessing() { function testItEnforcesExecutionLimitsBeforeQueueProcessing() {
@ -185,7 +172,6 @@ class SendingQueueTest extends \MailPoetTest {
$this->logger_factory, $this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class), Stub::makeEmpty(NewslettersRepository::class),
$this->cron_helper, $this->cron_helper,
$timer = false,
Stub::make( Stub::make(
new MailerTask(), new MailerTask(),
[ [
@ -202,7 +188,8 @@ class SendingQueueTest extends \MailPoetTest {
'newsletter_id' => 1, 'newsletter_id' => 1,
'subscriber_id' => 1, 'subscriber_id' => 1,
'queue_id' => $this->queue->id, 'queue_id' => $this->queue->id,
] ],
microtime(true)
); );
} }
@ -223,7 +210,6 @@ class SendingQueueTest extends \MailPoetTest {
$this->logger_factory, $this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class), Stub::makeEmpty(NewslettersRepository::class),
$this->cron_helper, $this->cron_helper,
$timer = false,
Stub::make( Stub::make(
new MailerTask(), new MailerTask(),
[ [
@ -240,7 +226,8 @@ class SendingQueueTest extends \MailPoetTest {
'newsletter_id' => 1, 'newsletter_id' => 1,
'subscriber_id' => 1, 'subscriber_id' => 1,
'queue_id' => $queue->id, 'queue_id' => $queue->id,
] ],
microtime(true)
); );
} }
@ -282,7 +269,6 @@ class SendingQueueTest extends \MailPoetTest {
$this->logger_factory, $this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]),
$this->cron_helper, $this->cron_helper,
$timer = false,
Stub::make( Stub::make(
new MailerTask(), new MailerTask(),
[ [
@ -313,7 +299,6 @@ class SendingQueueTest extends \MailPoetTest {
$this->logger_factory, $this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]),
$this->cron_helper, $this->cron_helper,
$timer = false,
Stub::make( Stub::make(
new MailerTask(), new MailerTask(),
[ [
@ -342,7 +327,6 @@ class SendingQueueTest extends \MailPoetTest {
$this->logger_factory, $this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]),
$this->cron_helper, $this->cron_helper,
$timer = false,
Stub::make( Stub::make(
new MailerTask(), new MailerTask(),
[ [
@ -390,7 +374,6 @@ class SendingQueueTest extends \MailPoetTest {
$this->logger_factory, $this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]),
$this->cron_helper, $this->cron_helper,
$timer = false,
Stub::make( Stub::make(
new MailerTask(), new MailerTask(),
[ [
@ -441,7 +424,6 @@ class SendingQueueTest extends \MailPoetTest {
$this->logger_factory, $this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]),
$this->cron_helper, $this->cron_helper,
$timer = false,
Stub::make( Stub::make(
new MailerTask(), new MailerTask(),
[ [
@ -499,7 +481,6 @@ class SendingQueueTest extends \MailPoetTest {
$this->logger_factory, $this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class), Stub::makeEmpty(NewslettersRepository::class),
$this->cron_helper, $this->cron_helper,
$timer = false,
Stub::makeEmpty(new MailerTask(), [], $this) Stub::makeEmpty(new MailerTask(), [], $this)
); );
$sending_queue_worker->process(); $sending_queue_worker->process();
@ -518,7 +499,6 @@ class SendingQueueTest extends \MailPoetTest {
$this->logger_factory, $this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]),
$this->cron_helper, $this->cron_helper,
$timer = false,
Stub::make( Stub::make(
new MailerTask(), new MailerTask(),
[ [
@ -571,7 +551,6 @@ class SendingQueueTest extends \MailPoetTest {
$this->logger_factory, $this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class), Stub::makeEmpty(NewslettersRepository::class),
$this->cron_helper, $this->cron_helper,
$timer = false,
Stub::make( Stub::make(
new MailerTask(), new MailerTask(),
[ [
@ -746,7 +725,6 @@ class SendingQueueTest extends \MailPoetTest {
$this->logger_factory, $this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class), Stub::makeEmpty(NewslettersRepository::class),
$this->cron_helper, $this->cron_helper,
$timer = false,
Stub::make( Stub::make(
new MailerTask(), new MailerTask(),
[ [
@ -760,7 +738,8 @@ class SendingQueueTest extends \MailPoetTest {
$prepared_subscribers = [], $prepared_subscribers = [],
$prepared_newsletters = [], $prepared_newsletters = [],
$prepared_subscribers = [], $prepared_subscribers = [],
$statistics = [] $statistics = [],
microtime(true)
); );
$this->fail('Paused sending exception was not thrown.'); $this->fail('Paused sending exception was not thrown.');
} catch (\Exception $e) { } catch (\Exception $e) {
@ -783,7 +762,6 @@ class SendingQueueTest extends \MailPoetTest {
$this->logger_factory, $this->logger_factory,
Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]),
$this->cron_helper, $this->cron_helper,
$timer = false,
Stub::make( Stub::make(
new MailerTask(), new MailerTask(),
[ [

View File

@ -35,15 +35,9 @@ class SimpleWorkerTest extends \MailPoetTest {
} }
} }
function testItConstructs() {
expect($this->worker->timer)->notEmpty();
}
function testItThrowsExceptionWhenExecutionLimitIsReached() { function testItThrowsExceptionWhenExecutionLimitIsReached() {
try { try {
new MockSimpleWorker( $this->worker->process(microtime(true) - $this->cron_helper->getDaemonExecutionLimit());
microtime(true) - $this->cron_helper->getDaemonExecutionLimit()
);
self::fail('Maximum execution time limit exception was not thrown.'); self::fail('Maximum execution time limit exception was not thrown.');
} catch (\Exception $e) { } catch (\Exception $e) {
expect($e->getMessage())->equals('Maximum execution time has been reached.'); expect($e->getMessage())->equals('Maximum execution time has been reached.');
@ -115,6 +109,7 @@ class SimpleWorkerTest extends \MailPoetTest {
['checkProcessingRequirements' => false], ['checkProcessingRequirements' => false],
$this $this
); );
$worker->__construct();
expect($worker->process())->false(); expect($worker->process())->false();
} }
@ -127,6 +122,7 @@ class SimpleWorkerTest extends \MailPoetTest {
], ],
$this $this
); );
$worker->__construct();
$worker->process(); $worker->process();
} }
@ -138,13 +134,13 @@ class SimpleWorkerTest extends \MailPoetTest {
function testItPreparesTask() { function testItPreparesTask() {
$task = $this->createScheduledTask(); $task = $this->createScheduledTask();
$this->worker->prepareTask($task); $this->worker->prepareTask($task, microtime(true));
expect($task->status)->null(); expect($task->status)->null();
} }
function testItProcessesTask() { function testItProcessesTask() {
$task = $this->createRunningTask(); $task = $this->createRunningTask();
$result = $this->worker->processTask($task); $result = $this->worker->processTask($task, microtime(true));
expect($task->status)->equals(ScheduledTask::STATUS_COMPLETED); expect($task->status)->equals(ScheduledTask::STATUS_COMPLETED);
expect($result)->equals(true); expect($result)->equals(true);
} }
@ -157,7 +153,7 @@ class SimpleWorkerTest extends \MailPoetTest {
['processTaskStrategy' => false], ['processTaskStrategy' => false],
$this $this
); );
$result = $worker->processTask($task); $result = $worker->processTask($task, microtime(true));
expect($task->status)->equals(null); expect($task->status)->equals(null);
expect($result)->equals(false); expect($result)->equals(false);
} }
@ -229,9 +225,9 @@ class SimpleWorkerTest extends \MailPoetTest {
->willReturn(true); ->willReturn(true);
$task = $this->createRunningTask(); $task = $this->createRunningTask();
expect(empty($task->in_progress))->equals(true); expect(empty($task->in_progress))->equals(true);
expect($worker->processTask($task))->equals(true); expect($worker->processTask($task, microtime(true)))->equals(true);
$task->in_progress = true; $task->in_progress = true;
expect($worker->processTask($task))->equals(false); expect($worker->processTask($task, microtime(true)))->equals(false);
} }
function testItWillResetTheInProgressFlagOnFail() { function testItWillResetTheInProgressFlagOnFail() {
@ -243,7 +239,7 @@ class SimpleWorkerTest extends \MailPoetTest {
->willThrowException(new \Exception('test error')); ->willThrowException(new \Exception('test error'));
$task = $this->createRunningTask(); $task = $this->createRunningTask();
try { try {
$worker->processTask($task); $worker->processTask($task, microtime(true));
$this->fail('An exception should be thrown'); $this->fail('An exception should be thrown');
} catch (\Exception $e) { } catch (\Exception $e) {
expect($e->getMessage())->equals('test error'); expect($e->getMessage())->equals('test error');
@ -260,11 +256,11 @@ class SimpleWorkerTest extends \MailPoetTest {
->willReturn(true); ->willReturn(true);
$task = $this->createRunningTask(); $task = $this->createRunningTask();
$task = ScheduledTask::findOne($task->id); // make sure `updated_at` is set by the DB $task = ScheduledTask::findOne($task->id); // make sure `updated_at` is set by the DB
expect($worker->processTask($task))->equals(true); expect($worker->processTask($task, microtime(true)))->equals(true);
$scheduled_at = $task->scheduled_at; $scheduled_at = $task->scheduled_at;
$task->updated_at = Carbon::createFromTimestamp(strtotime($task->updated_at)) $task->updated_at = Carbon::createFromTimestamp(strtotime($task->updated_at))
->subMinutes(MockSimpleWorker::TASK_RUN_TIMEOUT + 1); ->subMinutes(MockSimpleWorker::TASK_RUN_TIMEOUT + 1);
expect($worker->processTask($task))->equals(false); expect($worker->processTask($task, microtime(true)))->equals(false);
$task = ScheduledTask::findOne($task->id); $task = ScheduledTask::findOne($task->id);
expect($scheduled_at < $task->scheduled_at)->true(); expect($scheduled_at < $task->scheduled_at)->true();
expect($task->status)->equals(ScheduledTask::STATUS_SCHEDULED); expect($task->status)->equals(ScheduledTask::STATUS_SCHEDULED);

View File

@ -48,7 +48,7 @@ class UnsubscribeTokensTest extends \MailPoetTest {
function testItAddsTokensToSubscribers() { function testItAddsTokensToSubscribers() {
$worker = new UnsubscribeTokens(); $worker = new UnsubscribeTokens();
$worker->processTaskStrategy(ScheduledTask::createOrUpdate()); $worker->processTaskStrategy(ScheduledTask::createOrUpdate(), microtime(true));
$this->subscriber_with_token = Subscriber::findOne($this->subscriber_with_token->id); $this->subscriber_with_token = Subscriber::findOne($this->subscriber_with_token->id);
$this->subscriber_without_token = Subscriber::findOne($this->subscriber_without_token->id); $this->subscriber_without_token = Subscriber::findOne($this->subscriber_without_token->id);
expect($this->subscriber_with_token->unsubscribe_token)->equals('aaabbbcccdddeee'); expect($this->subscriber_with_token->unsubscribe_token)->equals('aaabbbcccdddeee');
@ -57,7 +57,7 @@ class UnsubscribeTokensTest extends \MailPoetTest {
function testItAddsTokensToNewsletters() { function testItAddsTokensToNewsletters() {
$worker = new UnsubscribeTokens(); $worker = new UnsubscribeTokens();
$worker->processTaskStrategy(ScheduledTask::createOrUpdate()); $worker->processTaskStrategy(ScheduledTask::createOrUpdate(), microtime(true));
$this->newsletter_with_token = Newsletter::findOne($this->newsletter_with_token->id); $this->newsletter_with_token = Newsletter::findOne($this->newsletter_with_token->id);
$this->newsletter_without_token = Newsletter::findOne($this->newsletter_without_token->id); $this->newsletter_without_token = Newsletter::findOne($this->newsletter_without_token->id);
expect($this->newsletter_with_token->unsubscribe_token)->equals('aaabbbcccdddeee'); expect($this->newsletter_with_token->unsubscribe_token)->equals('aaabbbcccdddeee');

View File

@ -31,7 +31,7 @@ class WooCommerceSyncTest extends \MailPoetTest {
$this->woocommerce_segment->expects($this->once()) $this->woocommerce_segment->expects($this->once())
->method('synchronizeCustomers'); ->method('synchronizeCustomers');
$task = $this->createScheduledTask(); $task = $this->createScheduledTask();
expect($this->worker->processTaskStrategy($task))->equals(true); expect($this->worker->processTaskStrategy($task, microtime(true)))->equals(true);
} }
private function createScheduledTask() { private function createScheduledTask() {