Skip to content

Commit

Permalink
Dynamic start times (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
SebKay authored Jun 18, 2024
1 parent 2d0a04c commit d5cb896
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions src/WPCronable.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ abstract class WPCronable

protected int $wp_cron_interval = 300; // 5 minutes

protected string $wp_cron_start = 'now';
protected string|array $wp_cron_start = 'now';

/**
* @return int|false
Expand All @@ -18,6 +18,36 @@ protected function wpCronNextRun()
return \wp_next_scheduled($this->wp_cron_name);
}

public function getCronStart(): string
{

$interval = Helpers::getCronScheduleByTime($this->wp_cron_interval);

if (! $interval) {
return '';
}

if (\is_string($this->wp_cron_start)) {
return "{$this->wp_cron_start} + {$interval['value']} seconds";
}

if (\is_array($this->wp_cron_start)) {
$times = \array_map(function ($time) {
return \strtotime($time);
}, $this->wp_cron_start);

$now = \strtotime('now');

foreach ($times as $time) {
if ($now < $time) {
return \date('Y-m-d H:i:s', $time);
}
}
}

return '';
}

public function scheduleCron(): void
{
\add_action($this->wp_cron_name, [$this, 'run']);
Expand All @@ -32,7 +62,7 @@ public function scheduleCron(): void
return;
}

\wp_schedule_event(\strtotime("{$this->wp_cron_start} + {$interval['value']} seconds"), $interval['slug'], $this->wp_cron_name);
\wp_schedule_event(\strtotime($this->getCronStart()), $interval['slug'], $this->wp_cron_name);
}

public function unscheduleCron(): void
Expand Down

0 comments on commit d5cb896

Please sign in to comment.