Skip to content

Commit d5cb896

Browse files
authored
Dynamic start times (#2)
1 parent 2d0a04c commit d5cb896

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

src/WPCronable.php

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ abstract class WPCronable
88

99
protected int $wp_cron_interval = 300; // 5 minutes
1010

11-
protected string $wp_cron_start = 'now';
11+
protected string|array $wp_cron_start = 'now';
1212

1313
/**
1414
* @return int|false
@@ -18,6 +18,36 @@ protected function wpCronNextRun()
1818
return \wp_next_scheduled($this->wp_cron_name);
1919
}
2020

21+
public function getCronStart(): string
22+
{
23+
24+
$interval = Helpers::getCronScheduleByTime($this->wp_cron_interval);
25+
26+
if (! $interval) {
27+
return '';
28+
}
29+
30+
if (\is_string($this->wp_cron_start)) {
31+
return "{$this->wp_cron_start} + {$interval['value']} seconds";
32+
}
33+
34+
if (\is_array($this->wp_cron_start)) {
35+
$times = \array_map(function ($time) {
36+
return \strtotime($time);
37+
}, $this->wp_cron_start);
38+
39+
$now = \strtotime('now');
40+
41+
foreach ($times as $time) {
42+
if ($now < $time) {
43+
return \date('Y-m-d H:i:s', $time);
44+
}
45+
}
46+
}
47+
48+
return '';
49+
}
50+
2151
public function scheduleCron(): void
2252
{
2353
\add_action($this->wp_cron_name, [$this, 'run']);
@@ -32,7 +62,7 @@ public function scheduleCron(): void
3262
return;
3363
}
3464

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

3868
public function unscheduleCron(): void

0 commit comments

Comments
 (0)