Skip to content

Commit

Permalink
perf(cron): Delay (re)checking timed jobs
Browse files Browse the repository at this point in the history
Signed-off-by: Christoph Wurst <christoph@winzerhof-wurst.at>
  • Loading branch information
ChristophWurst committed Feb 12, 2025
1 parent 167a78f commit 2bcc466
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/private/BackgroundJob/JobList.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Psr\Log\LoggerInterface;
use function get_class;
use function json_encode;
use function min;
use function strlen;

class JobList implements IJobList {
Expand Down Expand Up @@ -209,6 +210,26 @@ public function getNext(bool $onlyTimeSensitive = false, ?array $jobClasses = nu
return $this->getNext($onlyTimeSensitive);
}

if ($job instanceof \OCP\BackgroundJob\TimedJob) {
$now = $this->timeFactory->getTime();
$nextPossibleRun = $job->getLastRun() + $job->getInterval();
if ($now < $nextPossibleRun) {
// This job is not ready for execution yet. Set timestamps to the future to avoid
// re-checking with every cron run.
// To avoid bugs that lead to jobs never executing again, the future timestamp is
// capped at two days.
$nextCheck = min($nextPossibleRun, $now + 48 * 3600);
$updateTimedJob = $this->connection->getQueryBuilder();
$updateTimedJob->update('jobs')
->set('last_checked', $updateTimedJob->createNamedParameter($nextCheck, IQueryBuilder::PARAM_INT))
->where($updateTimedJob->expr()->eq('id', $updateTimedJob->createParameter('jobid')));
$updateTimedJob->setParameter('jobid', $row['id']);
$updateTimedJob->executeStatement();

return $this->getNext($onlyTimeSensitive, $jobClasses);
}
}

$update = $this->connection->getQueryBuilder();
$update->update('jobs')
->set('reserved_at', $update->createNamedParameter($this->timeFactory->getTime()))
Expand Down
9 changes: 9 additions & 0 deletions lib/public/BackgroundJob/TimedJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ public function setInterval(int $seconds) {
$this->interval = $seconds;
}

/**
* Get the interval [seconds] for the job
*
* @since 32.0.0
*/
public function getInterval(): int {
return $this->interval;
}

/**
* Whether the background job is time sensitive and needs to run soon after
* the scheduled interval, of if it is okay to be delayed until a later time.
Expand Down

0 comments on commit 2bcc466

Please sign in to comment.