Skip to content

Commit 8638f3b

Browse files
committed
feat(occ): add 'stop_after' option to stop the worker after some time
Signed-off-by: Julien Veyssier <[email protected]>
1 parent c8e09d1 commit 8638f3b

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

core/Command/Background/JobWorker.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,25 @@ protected function configure(): void {
5252
'Interval in seconds in which the worker should repeat already processed jobs (set to 0 for no repeat)',
5353
5
5454
)
55+
->addOption(
56+
'stop_after',
57+
't',
58+
InputOption::VALUE_OPTIONAL,
59+
'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)'
60+
)
5561
;
5662
}
5763

5864
protected function execute(InputInterface $input, OutputInterface $output): int {
65+
$startTime = time();
66+
$stopAfterOptionValue = $input->getOption('stop_after');
67+
$stopAfterSeconds = $stopAfterOptionValue === null
68+
? null
69+
: $this->parseStopAfter($stopAfterOptionValue);
70+
if ($stopAfterSeconds !== null) {
71+
$output->writeln('<info>Background job worker will stop after ' . $stopAfterSeconds . ' seconds</info>');
72+
}
73+
5974
$jobClasses = $input->getArgument('job-classes');
6075
$jobClasses = empty($jobClasses) ? null : $jobClasses;
6176

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

7287
while (true) {
88+
// Stop if we exceeded stop_after value
89+
if ($stopAfterSeconds !== null && ($startTime + $stopAfterSeconds) < time()) {
90+
$output->writeln('stop_after time has been exceeded, exiting...', OutputInterface::VERBOSITY_VERBOSE);
91+
break;
92+
}
7393
// Handle canceling of the process
7494
try {
7595
$this->abortIfInterrupted();
@@ -137,4 +157,20 @@ private function printSummary(InputInterface $input, OutputInterface $output): v
137157
}
138158
$this->writeTableInOutputFormat($input, $output, $counts);
139159
}
160+
161+
private function parseStopAfter(string $value): ?int {
162+
if (is_numeric($value)) {
163+
return (int) $value;
164+
}
165+
if (preg_match("/^(\d+)s$/i", $value, $matches)) {
166+
return (int) $matches[0];
167+
}
168+
if (preg_match("/^(\d+)m$/i", $value, $matches)) {
169+
return 60 * ((int) $matches[0]);
170+
}
171+
if (preg_match("/^(\d+)h$/i", $value, $matches)) {
172+
return 60 * 60 * ((int) $matches[0]);
173+
}
174+
return null;
175+
}
140176
}

0 commit comments

Comments
 (0)