Moodle release 3.4.1
[moodle.git] / lib / cronlib.php
blob4ce1c698836674645f7d8d5ea4012808681373b4
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Cron functions.
20 * @package core
21 * @subpackage admin
22 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 /**
27 * Execute cron tasks
29 function cron_run() {
30 global $DB, $CFG, $OUTPUT;
32 if (CLI_MAINTENANCE) {
33 echo "CLI maintenance mode active, cron execution suspended.\n";
34 exit(1);
37 if (moodle_needs_upgrading()) {
38 echo "Moodle upgrade pending, cron execution suspended.\n";
39 exit(1);
42 require_once($CFG->libdir.'/adminlib.php');
44 if (!empty($CFG->showcronsql)) {
45 $DB->set_debug(true);
47 if (!empty($CFG->showcrondebugging)) {
48 set_debugging(DEBUG_DEVELOPER, true);
51 core_php_time_limit::raise();
52 $starttime = microtime();
54 // Increase memory limit
55 raise_memory_limit(MEMORY_EXTRA);
57 // Emulate normal session - we use admin accoutn by default
58 cron_setup_user();
60 // Start output log
61 $timenow = time();
62 mtrace("Server Time: ".date('r', $timenow)."\n\n");
64 // Run all scheduled tasks.
65 while (!\core\task\manager::static_caches_cleared_since($timenow) &&
66 $task = \core\task\manager::get_next_scheduled_task($timenow)) {
67 cron_run_inner_scheduled_task($task);
68 unset($task);
71 // Run all adhoc tasks.
72 while (!\core\task\manager::static_caches_cleared_since($timenow) &&
73 $task = \core\task\manager::get_next_adhoc_task($timenow)) {
74 cron_run_inner_adhoc_task($task);
75 unset($task);
78 mtrace("Cron script completed correctly");
80 gc_collect_cycles();
81 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
82 $difftime = microtime_diff($starttime, microtime());
83 mtrace("Execution took ".$difftime." seconds");
86 /**
87 * Shared code that handles running of a single scheduled task within the cron.
89 * Not intended for calling directly outside of this library!
91 * @param \core\task\task_base $task
93 function cron_run_inner_scheduled_task(\core\task\task_base $task) {
94 global $CFG, $DB;
96 $fullname = $task->get_name() . ' (' . get_class($task) . ')';
97 mtrace('Execute scheduled task: ' . $fullname);
98 cron_trace_time_and_memory();
99 $predbqueries = null;
100 $predbqueries = $DB->perf_get_queries();
101 $pretime = microtime(1);
102 try {
103 get_mailer('buffer');
104 $task->execute();
105 if ($DB->is_transaction_started()) {
106 throw new coding_exception("Task left transaction open");
108 if (isset($predbqueries)) {
109 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
110 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
112 mtrace('Scheduled task complete: ' . $fullname);
113 \core\task\manager::scheduled_task_complete($task);
114 } catch (Exception $e) {
115 if ($DB && $DB->is_transaction_started()) {
116 error_log('Database transaction aborted automatically in ' . get_class($task));
117 $DB->force_transaction_rollback();
119 if (isset($predbqueries)) {
120 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
121 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
123 mtrace('Scheduled task failed: ' . $fullname . ',' . $e->getMessage());
124 if ($CFG->debugdeveloper) {
125 if (!empty($e->debuginfo)) {
126 mtrace("Debug info:");
127 mtrace($e->debuginfo);
129 mtrace("Backtrace:");
130 mtrace(format_backtrace($e->getTrace(), true));
132 \core\task\manager::scheduled_task_failed($task);
134 get_mailer('close');
138 * Shared code that handles running of a single adhoc task within the cron.
140 * @param \core\task\adhoc_task $task
142 function cron_run_inner_adhoc_task(\core\task\adhoc_task $task) {
143 global $DB, $CFG;
144 mtrace("Execute adhoc task: " . get_class($task));
145 cron_trace_time_and_memory();
146 $predbqueries = null;
147 $predbqueries = $DB->perf_get_queries();
148 $pretime = microtime(1);
150 if ($userid = $task->get_userid()) {
151 // This task has a userid specified.
152 if ($user = \core_user::get_user($userid)) {
153 // User found. Check that they are suitable.
154 try {
155 \core_user::require_active_user($user, true, true);
156 } catch (moodle_exception $e) {
157 mtrace("User {$userid} cannot be used to run an adhoc task: " . get_class($task) . ". Cancelling task.");
158 $user = null;
160 } else {
161 // Unable to find the user for this task.
162 // A user missing in the database will never reappear.
163 mtrace("User {$userid} could not be found for adhoc task: " . get_class($task) . ". Cancelling task.");
166 if (empty($user)) {
167 // A user missing in the database will never reappear so the task needs to be failed to ensure that locks are removed,
168 // and then removed to prevent future runs.
169 // A task running as a user should only be run as that user.
170 \core\task\manager::adhoc_task_failed($task);
171 $DB->delete_records('task_adhoc', ['id' => $task->get_id()]);
173 return;
176 cron_setup_user($user);
179 try {
180 get_mailer('buffer');
181 $task->execute();
182 if ($DB->is_transaction_started()) {
183 throw new coding_exception("Task left transaction open");
185 if (isset($predbqueries)) {
186 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
187 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
189 mtrace("Adhoc task complete: " . get_class($task));
190 \core\task\manager::adhoc_task_complete($task);
191 } catch (Exception $e) {
192 if ($DB && $DB->is_transaction_started()) {
193 error_log('Database transaction aborted automatically in ' . get_class($task));
194 $DB->force_transaction_rollback();
196 if (isset($predbqueries)) {
197 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
198 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
200 mtrace("Adhoc task failed: " . get_class($task) . "," . $e->getMessage());
201 if ($CFG->debugdeveloper) {
202 if (!empty($e->debuginfo)) {
203 mtrace("Debug info:");
204 mtrace($e->debuginfo);
206 mtrace("Backtrace:");
207 mtrace(format_backtrace($e->getTrace(), true));
209 \core\task\manager::adhoc_task_failed($task);
210 } finally {
211 // Reset back to the standard admin user.
212 cron_setup_user();
214 get_mailer('close');
218 * Runs a single cron task. This function assumes it is displaying output in pseudo-CLI mode.
220 * The function will fail if the task is disabled.
222 * Warning: Because this function closes the browser session, it may not be safe to continue
223 * with other processing (other than displaying the rest of the page) after using this function!
225 * @param \core\task\scheduled_task $task Task to run
226 * @return bool True if cron run successful
228 function cron_run_single_task(\core\task\scheduled_task $task) {
229 global $CFG, $DB, $USER;
231 if (CLI_MAINTENANCE) {
232 echo "CLI maintenance mode active, cron execution suspended.\n";
233 return false;
236 if (moodle_needs_upgrading()) {
237 echo "Moodle upgrade pending, cron execution suspended.\n";
238 return false;
241 // Check task and component is not disabled.
242 $taskname = get_class($task);
243 if ($task->get_disabled()) {
244 echo "Task is disabled ($taskname).\n";
245 return false;
247 $component = $task->get_component();
248 if ($plugininfo = core_plugin_manager::instance()->get_plugin_info($component)) {
249 if ($plugininfo->is_enabled() === false && !$task->get_run_if_component_disabled()) {
250 echo "Component is not enabled ($component).\n";
251 return false;
255 // Enable debugging features as per config settings.
256 if (!empty($CFG->showcronsql)) {
257 $DB->set_debug(true);
259 if (!empty($CFG->showcrondebugging)) {
260 set_debugging(DEBUG_DEVELOPER, true);
263 // Increase time and memory limits.
264 core_php_time_limit::raise();
265 raise_memory_limit(MEMORY_EXTRA);
267 // Switch to admin account for cron tasks, but close the session so we don't send this stuff
268 // to the browser.
269 session_write_close();
270 $realuser = clone($USER);
271 cron_setup_user(null, null, true);
273 // Get lock for cron task.
274 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
275 if (!$cronlock = $cronlockfactory->get_lock('core_cron', 1)) {
276 echo "Unable to get cron lock.\n";
277 return false;
279 if (!$lock = $cronlockfactory->get_lock($taskname, 1)) {
280 $cronlock->release();
281 echo "Unable to get task lock for $taskname.\n";
282 return false;
284 $task->set_lock($lock);
285 if (!$task->is_blocking()) {
286 $cronlock->release();
287 } else {
288 $task->set_cron_lock($cronlock);
291 // Run actual tasks.
292 cron_run_inner_scheduled_task($task);
294 // Go back to real user account.
295 cron_setup_user($realuser, null, true);
297 return true;
301 * Output some standard information during cron runs. Specifically current time
302 * and memory usage. This method also does gc_collect_cycles() (before displaying
303 * memory usage) to try to help PHP manage memory better.
305 function cron_trace_time_and_memory() {
306 gc_collect_cycles();
307 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
311 * Executes cron functions for a specific type of plugin.
313 * @param string $plugintype Plugin type (e.g. 'report')
314 * @param string $description If specified, will display 'Starting (whatever)'
315 * and 'Finished (whatever)' lines, otherwise does not display
317 function cron_execute_plugin_type($plugintype, $description = null) {
318 global $DB;
320 // Get list from plugin => function for all plugins
321 $plugins = get_plugin_list_with_function($plugintype, 'cron');
323 // Modify list for backward compatibility (different files/names)
324 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
326 // Return if no plugins with cron function to process
327 if (!$plugins) {
328 return;
331 if ($description) {
332 mtrace('Starting '.$description);
335 foreach ($plugins as $component=>$cronfunction) {
336 $dir = core_component::get_component_directory($component);
338 // Get cron period if specified in version.php, otherwise assume every cron
339 $cronperiod = 0;
340 if (file_exists("$dir/version.php")) {
341 $plugin = new stdClass();
342 include("$dir/version.php");
343 if (isset($plugin->cron)) {
344 $cronperiod = $plugin->cron;
348 // Using last cron and cron period, don't run if it already ran recently
349 $lastcron = get_config($component, 'lastcron');
350 if ($cronperiod && $lastcron) {
351 if ($lastcron + $cronperiod > time()) {
352 // do not execute cron yet
353 continue;
357 mtrace('Processing cron function for ' . $component . '...');
358 cron_trace_time_and_memory();
359 $pre_dbqueries = $DB->perf_get_queries();
360 $pre_time = microtime(true);
362 $cronfunction();
364 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
365 round(microtime(true) - $pre_time, 2) . " seconds)");
367 set_config('lastcron', time(), $component);
368 core_php_time_limit::raise();
371 if ($description) {
372 mtrace('Finished ' . $description);
377 * Used to add in old-style cron functions within plugins that have not been converted to the
378 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
379 * cron.php and some used a different name.)
381 * @param string $plugintype Plugin type e.g. 'report'
382 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
383 * 'report_frog_cron') for plugin cron functions that were already found using the new API
384 * @return array Revised version of $plugins that adds in any extra plugin functions found by
385 * looking in the older location
387 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
388 global $CFG; // mandatory in case it is referenced by include()d PHP script
390 if ($plugintype === 'report') {
391 // Admin reports only - not course report because course report was
392 // never implemented before, so doesn't need BC
393 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
394 $component = $plugintype . '_' . $pluginname;
395 if (isset($plugins[$component])) {
396 // We already have detected the function using the new API
397 continue;
399 if (!file_exists("$dir/cron.php")) {
400 // No old style cron file present
401 continue;
403 include_once("$dir/cron.php");
404 $cronfunction = $component . '_cron';
405 if (function_exists($cronfunction)) {
406 $plugins[$component] = $cronfunction;
407 } else {
408 debugging("Invalid legacy cron.php detected in $component, " .
409 "please use lib.php instead");
412 } else if (strpos($plugintype, 'grade') === 0) {
413 // Detect old style cron function names
414 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
415 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
416 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
417 $component = $plugintype.'_'.$pluginname;
418 if (isset($plugins[$component])) {
419 // We already have detected the function using the new API
420 continue;
422 if (!file_exists("$dir/lib.php")) {
423 continue;
425 include_once("$dir/lib.php");
426 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
427 $pluginname . '_cron';
428 if (function_exists($cronfunction)) {
429 $plugins[$component] = $cronfunction;
434 return $plugins;