Skip to content

Commit

Permalink
MDL-66925 cron: Add cli option to keep adhoc task runner alive
Browse files Browse the repository at this point in the history
  • Loading branch information
brendanheywood committed Nov 30, 2019
1 parent 800563e commit ad17190
Showing 1 changed file with 49 additions and 15 deletions.
64 changes: 49 additions & 15 deletions admin/tool/task/cli/adhoc_task.php
Expand Up @@ -32,10 +32,13 @@
[
'execute' => false,
'help' => false,
'keep-alive' => 0,
'showsql' => false,
'showdebugging' => false,
], [
'h' => 'help',
'e' => 'execute',
'k' => 'keep-alive',
]
);

Expand All @@ -45,19 +48,20 @@
}

if ($options['help'] or empty($options['execute'])) {
$help =
"Scheduled cron tasks.
$help = <<<EOT
Ad hoc cron tasks.
Options:
--showsql Show sql queries before they are executed
--showdebugging Show developer level debugging information
--execute Run all queued adhoc tasks
-h, --help Print out this help
-h, --help Print out this help
--showsql Show sql queries before they are executed
--showdebugging Show developer level debugging information
-e, --execute Run all queued adhoc tasks
-k, --keep-alive=N Keep this script alive for N seconds and poll for new adhoc tasks
Example:
\$sudo -u www-data /usr/bin/php admin/tool/task/cli/adhoc_task.php --execute
";
EOT;

echo $help;
die;
Expand All @@ -84,6 +88,9 @@
if (empty($options['execute'])) {
exit(0);
}
if (empty($options['keep-alive'])) {
$options['keep-alive'] = 0;
}

if (!empty($CFG->showcronsql)) {
$DB->set_debug(true);
Expand All @@ -93,25 +100,52 @@
}

core_php_time_limit::raise();
$starttime = microtime();

// Increase memory limit.
raise_memory_limit(MEMORY_EXTRA);

// Emulate normal session - we use admin accoutn by default.
// Emulate normal session - we use admin account by default.
cron_setup_user();

// Start output log.
$timenow = time();
$timestart = time();
$timenow = $timestart;
$finishtime = $timenow + (int)$options['keep-alive'];
$humantimenow = date('r', $timenow);
mtrace("Server Time: {$humantimenow}\n");

// Run all adhoc tasks.
$taskcount = 0;
while (!\core\task\manager::static_caches_cleared_since($timenow) &&
$task = \core\task\manager::get_next_adhoc_task($timenow)) {
cron_run_inner_adhoc_task($task);
$taskcount++;
unset($task);
$waiting = false;
while (!\core\task\manager::static_caches_cleared_since($timestart)) {

$task = \core\task\manager::get_next_adhoc_task($timenow);

if ($task) {
if ($waiting) {
cli_writeln('');
}
$waiting = false;
cron_run_inner_adhoc_task($task);
$taskcount++;
unset($task);
} else {
if (time() > $finishtime) {
break;
}
if (!$waiting) {
cli_write('Waiting for more adhoc tasks to be queued ');
} else {
cli_write('.');
}
$waiting = true;
sleep(1);
$timenow = time();
}
}
if ($waiting) {
cli_writeln('');
}

mtrace("Ran {$taskcount} adhoc tasks found at {$humantimenow}");

0 comments on commit ad17190

Please sign in to comment.