MDL-49743 singleview: slightly clarify logic
[moodle.git] / lib / cronlib.php
blobe6e6b464476968b230a720b8263d8dd218566faf
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 mtrace("Execute scheduled task: " . $task->get_name());
68 cron_trace_time_and_memory();
69 $predbqueries = null;
70 $predbqueries = $DB->perf_get_queries();
71 $pretime = microtime(1);
72 try {
73 get_mailer('buffer');
74 $task->execute();
75 if ($DB->is_transaction_started()) {
76 throw new coding_exception("Task left transaction open");
78 if (isset($predbqueries)) {
79 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
80 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
82 mtrace("Scheduled task complete: " . $task->get_name());
83 \core\task\manager::scheduled_task_complete($task);
84 } catch (Exception $e) {
85 if ($DB && $DB->is_transaction_started()) {
86 error_log('Database transaction aborted automatically in ' . get_class($task));
87 $DB->force_transaction_rollback();
89 if (isset($predbqueries)) {
90 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
91 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
93 mtrace("Scheduled task failed: " . $task->get_name() . "," . $e->getMessage());
94 if ($CFG->debugdeveloper) {
95 if (!empty($e->debuginfo)) {
96 mtrace("Debug info:");
97 mtrace($e->debuginfo);
99 mtrace("Backtrace:");
100 mtrace(format_backtrace($e->getTrace(), true));
102 \core\task\manager::scheduled_task_failed($task);
104 get_mailer('close');
105 unset($task);
108 // Run all adhoc tasks.
109 while (!\core\task\manager::static_caches_cleared_since($timenow) &&
110 $task = \core\task\manager::get_next_adhoc_task($timenow)) {
111 mtrace("Execute adhoc task: " . get_class($task));
112 cron_trace_time_and_memory();
113 $predbqueries = null;
114 $predbqueries = $DB->perf_get_queries();
115 $pretime = microtime(1);
116 try {
117 get_mailer('buffer');
118 $task->execute();
119 if ($DB->is_transaction_started()) {
120 throw new coding_exception("Task left transaction open");
122 if (isset($predbqueries)) {
123 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
124 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
126 mtrace("Adhoc task complete: " . get_class($task));
127 \core\task\manager::adhoc_task_complete($task);
128 } catch (Exception $e) {
129 if ($DB && $DB->is_transaction_started()) {
130 error_log('Database transaction aborted automatically in ' . get_class($task));
131 $DB->force_transaction_rollback();
133 if (isset($predbqueries)) {
134 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
135 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
137 mtrace("Adhoc task failed: " . get_class($task) . "," . $e->getMessage());
138 if ($CFG->debugdeveloper) {
139 if (!empty($e->debuginfo)) {
140 mtrace("Debug info:");
141 mtrace($e->debuginfo);
143 mtrace("Backtrace:");
144 mtrace(format_backtrace($e->getTrace(), true));
146 \core\task\manager::adhoc_task_failed($task);
148 get_mailer('close');
149 unset($task);
152 mtrace("Cron script completed correctly");
154 gc_collect_cycles();
155 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
156 $difftime = microtime_diff($starttime, microtime());
157 mtrace("Execution took ".$difftime." seconds");
161 * Output some standard information during cron runs. Specifically current time
162 * and memory usage. This method also does gc_collect_cycles() (before displaying
163 * memory usage) to try to help PHP manage memory better.
165 function cron_trace_time_and_memory() {
166 gc_collect_cycles();
167 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
171 * Executes cron functions for a specific type of plugin.
173 * @param string $plugintype Plugin type (e.g. 'report')
174 * @param string $description If specified, will display 'Starting (whatever)'
175 * and 'Finished (whatever)' lines, otherwise does not display
177 function cron_execute_plugin_type($plugintype, $description = null) {
178 global $DB;
180 // Get list from plugin => function for all plugins
181 $plugins = get_plugin_list_with_function($plugintype, 'cron');
183 // Modify list for backward compatibility (different files/names)
184 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
186 // Return if no plugins with cron function to process
187 if (!$plugins) {
188 return;
191 if ($description) {
192 mtrace('Starting '.$description);
195 foreach ($plugins as $component=>$cronfunction) {
196 $dir = core_component::get_component_directory($component);
198 // Get cron period if specified in version.php, otherwise assume every cron
199 $cronperiod = 0;
200 if (file_exists("$dir/version.php")) {
201 $plugin = new stdClass();
202 include("$dir/version.php");
203 if (isset($plugin->cron)) {
204 $cronperiod = $plugin->cron;
208 // Using last cron and cron period, don't run if it already ran recently
209 $lastcron = get_config($component, 'lastcron');
210 if ($cronperiod && $lastcron) {
211 if ($lastcron + $cronperiod > time()) {
212 // do not execute cron yet
213 continue;
217 mtrace('Processing cron function for ' . $component . '...');
218 cron_trace_time_and_memory();
219 $pre_dbqueries = $DB->perf_get_queries();
220 $pre_time = microtime(true);
222 $cronfunction();
224 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
225 round(microtime(true) - $pre_time, 2) . " seconds)");
227 set_config('lastcron', time(), $component);
228 core_php_time_limit::raise();
231 if ($description) {
232 mtrace('Finished ' . $description);
237 * Used to add in old-style cron functions within plugins that have not been converted to the
238 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
239 * cron.php and some used a different name.)
241 * @param string $plugintype Plugin type e.g. 'report'
242 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
243 * 'report_frog_cron') for plugin cron functions that were already found using the new API
244 * @return array Revised version of $plugins that adds in any extra plugin functions found by
245 * looking in the older location
247 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
248 global $CFG; // mandatory in case it is referenced by include()d PHP script
250 if ($plugintype === 'report') {
251 // Admin reports only - not course report because course report was
252 // never implemented before, so doesn't need BC
253 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
254 $component = $plugintype . '_' . $pluginname;
255 if (isset($plugins[$component])) {
256 // We already have detected the function using the new API
257 continue;
259 if (!file_exists("$dir/cron.php")) {
260 // No old style cron file present
261 continue;
263 include_once("$dir/cron.php");
264 $cronfunction = $component . '_cron';
265 if (function_exists($cronfunction)) {
266 $plugins[$component] = $cronfunction;
267 } else {
268 debugging("Invalid legacy cron.php detected in $component, " .
269 "please use lib.php instead");
272 } else if (strpos($plugintype, 'grade') === 0) {
273 // Detect old style cron function names
274 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
275 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
276 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
277 $component = $plugintype.'_'.$pluginname;
278 if (isset($plugins[$component])) {
279 // We already have detected the function using the new API
280 continue;
282 if (!file_exists("$dir/lib.php")) {
283 continue;
285 include_once("$dir/lib.php");
286 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
287 $pluginname . '_cron';
288 if (function_exists($cronfunction)) {
289 $plugins[$component] = $cronfunction;
294 return $plugins;