爬虫开发
This commit is contained in:
44
app/Services/Crawler/CrawlRuleScheduleService.php
Normal file
44
app/Services/Crawler/CrawlRuleScheduleService.php
Normal file
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Crawler;
|
||||
|
||||
use App\Models\CrawlRule;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Cron\CronExpression;
|
||||
|
||||
class CrawlRuleScheduleService
|
||||
{
|
||||
public function isDue(CrawlRule $rule, ?CarbonImmutable $now = null): bool
|
||||
{
|
||||
if (! $rule->enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$now ??= CarbonImmutable::now($rule->timezone ?: 'Asia/Shanghai');
|
||||
|
||||
try {
|
||||
$cron = new CronExpression($rule->cron_expression);
|
||||
} catch (\Throwable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $cron->isDue($now);
|
||||
}
|
||||
|
||||
public function nextRunAt(CrawlRule $rule, ?CarbonImmutable $from = null): ?CarbonImmutable
|
||||
{
|
||||
$from ??= CarbonImmutable::now($rule->timezone ?: 'Asia/Shanghai');
|
||||
|
||||
try {
|
||||
$cron = new CronExpression($rule->cron_expression);
|
||||
$next = CarbonImmutable::instance($cron->getNextRunDate($from));
|
||||
} catch (\Throwable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $next->setTimezone('UTC');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user