Skip to content

Commit

Permalink
Merge pull request #47277 from nextcloud/enh/noid/occ-bg-job-worker-m…
Browse files Browse the repository at this point in the history
…ax-time

[occ:bg-job:worker] Add 'stop_after' option
  • Loading branch information
julien-nc authored Aug 16, 2024
2 parents c8e09d1 + 8638f3b commit 8d49681
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions core/Command/Background/JobWorker.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,25 @@ protected function configure(): void {
'Interval in seconds in which the worker should repeat already processed jobs (set to 0 for no repeat)',
5
)
->addOption(
'stop_after',
't',
InputOption::VALUE_OPTIONAL,
'Duration after which the worker should stop and exit. The worker won\'t kill a potential running job, it will exit after this job has finished running (supported values are: "30" or "30s" for 30 seconds, "10m" for 10 minutes and "2h" for 2 hours)'
)
;
}

protected function execute(InputInterface $input, OutputInterface $output): int {
$startTime = time();
$stopAfterOptionValue = $input->getOption('stop_after');
$stopAfterSeconds = $stopAfterOptionValue === null
? null
: $this->parseStopAfter($stopAfterOptionValue);
if ($stopAfterSeconds !== null) {
$output->writeln('<info>Background job worker will stop after ' . $stopAfterSeconds . ' seconds</info>');
}

$jobClasses = $input->getArgument('job-classes');
$jobClasses = empty($jobClasses) ? null : $jobClasses;

Expand All @@ -70,6 +85,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}

while (true) {
// Stop if we exceeded stop_after value
if ($stopAfterSeconds !== null && ($startTime + $stopAfterSeconds) < time()) {
$output->writeln('stop_after time has been exceeded, exiting...', OutputInterface::VERBOSITY_VERBOSE);
break;
}
// Handle canceling of the process
try {
$this->abortIfInterrupted();
Expand Down Expand Up @@ -137,4 +157,20 @@ private function printSummary(InputInterface $input, OutputInterface $output): v
}
$this->writeTableInOutputFormat($input, $output, $counts);
}

private function parseStopAfter(string $value): ?int {
if (is_numeric($value)) {
return (int) $value;
}
if (preg_match("/^(\d+)s$/i", $value, $matches)) {
return (int) $matches[0];
}
if (preg_match("/^(\d+)m$/i", $value, $matches)) {
return 60 * ((int) $matches[0]);
}
if (preg_match("/^(\d+)h$/i", $value, $matches)) {
return 60 * 60 * ((int) $matches[0]);
}
return null;
}
}

0 comments on commit 8d49681

Please sign in to comment.