Skip to content

Commit 8e3a049

Browse files
Merge pull request #45804 from nextcloud/fix/cron/log-long-running-jobs
fix(cron): Log long running jobs
2 parents f626476 + 7ea6eac commit 8e3a049

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

cron.php

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,15 +154,34 @@
154154
$jobDetails = get_class($job) . ' (id: ' . $job->getId() . ', arguments: ' . json_encode($job->getArgument()) . ')';
155155
$logger->debug('CLI cron call has selected job ' . $jobDetails, ['app' => 'cron']);
156156

157+
$timeBefore = time();
157158
$memoryBefore = memory_get_usage();
158159
$memoryPeakBefore = memory_get_peak_usage();
159160

160161
/** @psalm-suppress DeprecatedMethod Calling execute until it is removed, then will switch to start */
161162
$job->execute($jobList);
162163

164+
$timeAfter = time();
163165
$memoryAfter = memory_get_usage();
164166
$memoryPeakAfter = memory_get_peak_usage();
165167

168+
$cronInterval = 5 * 60;
169+
$timeSpent = $timeAfter - $timeBefore;
170+
if ($timeSpent > $cronInterval) {
171+
$logLevel = match (true) {
172+
$timeSpent > $cronInterval * 128 => \OCP\ILogger::FATAL,
173+
$timeSpent > $cronInterval * 64 => \OCP\ILogger::ERROR,
174+
$timeSpent > $cronInterval * 16 => \OCP\ILogger::WARN,
175+
$timeSpent > $cronInterval * 8 => \OCP\ILogger::INFO,
176+
default => \OCP\ILogger::DEBUG,
177+
};
178+
$logger->log(
179+
$logLevel,
180+
'Background job ' . $jobDetails . ' ran for ' . $timeSpent . ' seconds',
181+
['app' => 'cron']
182+
);
183+
}
184+
166185
if ($memoryAfter - $memoryBefore > 10_000_000) {
167186
$logger->warning('Used memory grew by more than 10 MB when executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryAfter). ' (before: ' . Util::humanFileSize($memoryBefore) . ')', ['app' => 'cron']);
168187
}
@@ -178,7 +197,7 @@
178197
$executedJobs[$job->getId()] = true;
179198
unset($job);
180199

181-
if (time() > $endTime) {
200+
if ($timeAfter > $endTime) {
182201
break;
183202
}
184203
}

0 commit comments

Comments
 (0)