Merge branch 'MDL-47896-master' of git://github.com/zbdd/moodle
[moodle.git] / lib / cronlib.php
blob4312ba6900c17e2ded148cea56bfb7cea10c2c39
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 $task->execute();
74 if (isset($predbqueries)) {
75 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
76 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
78 mtrace("Scheduled task complete: " . $task->get_name());
79 \core\task\manager::scheduled_task_complete($task);
80 } catch (Exception $e) {
81 if ($DB && $DB->is_transaction_started()) {
82 error_log('Database transaction aborted automatically in ' . get_class($task));
83 $DB->force_transaction_rollback();
85 if (isset($predbqueries)) {
86 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
87 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
89 mtrace("Scheduled task failed: " . $task->get_name() . "," . $e->getMessage());
90 \core\task\manager::scheduled_task_failed($task);
92 unset($task);
95 // Run all adhoc tasks.
96 while (!\core\task\manager::static_caches_cleared_since($timenow) &&
97 $task = \core\task\manager::get_next_adhoc_task($timenow)) {
98 mtrace("Execute adhoc task: " . get_class($task));
99 cron_trace_time_and_memory();
100 $predbqueries = null;
101 $predbqueries = $DB->perf_get_queries();
102 $pretime = microtime(1);
103 try {
104 $task->execute();
105 if (isset($predbqueries)) {
106 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
107 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
109 mtrace("Adhoc task complete: " . get_class($task));
110 \core\task\manager::adhoc_task_complete($task);
111 } catch (Exception $e) {
112 if ($DB && $DB->is_transaction_started()) {
113 error_log('Database transaction aborted automatically in ' . get_class($task));
114 $DB->force_transaction_rollback();
116 if (isset($predbqueries)) {
117 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
118 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
120 mtrace("Adhoc task failed: " . get_class($task) . "," . $e->getMessage());
121 \core\task\manager::adhoc_task_failed($task);
123 unset($task);
126 mtrace("Cron script completed correctly");
128 gc_collect_cycles();
129 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
130 $difftime = microtime_diff($starttime, microtime());
131 mtrace("Execution took ".$difftime." seconds");
135 * Output some standard information during cron runs. Specifically current time
136 * and memory usage. This method also does gc_collect_cycles() (before displaying
137 * memory usage) to try to help PHP manage memory better.
139 function cron_trace_time_and_memory() {
140 gc_collect_cycles();
141 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
145 * Executes cron functions for a specific type of plugin.
147 * @param string $plugintype Plugin type (e.g. 'report')
148 * @param string $description If specified, will display 'Starting (whatever)'
149 * and 'Finished (whatever)' lines, otherwise does not display
151 function cron_execute_plugin_type($plugintype, $description = null) {
152 global $DB;
154 // Get list from plugin => function for all plugins
155 $plugins = get_plugin_list_with_function($plugintype, 'cron');
157 // Modify list for backward compatibility (different files/names)
158 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
160 // Return if no plugins with cron function to process
161 if (!$plugins) {
162 return;
165 if ($description) {
166 mtrace('Starting '.$description);
169 foreach ($plugins as $component=>$cronfunction) {
170 $dir = core_component::get_component_directory($component);
172 // Get cron period if specified in version.php, otherwise assume every cron
173 $cronperiod = 0;
174 if (file_exists("$dir/version.php")) {
175 $plugin = new stdClass();
176 include("$dir/version.php");
177 if (isset($plugin->cron)) {
178 $cronperiod = $plugin->cron;
182 // Using last cron and cron period, don't run if it already ran recently
183 $lastcron = get_config($component, 'lastcron');
184 if ($cronperiod && $lastcron) {
185 if ($lastcron + $cronperiod > time()) {
186 // do not execute cron yet
187 continue;
191 mtrace('Processing cron function for ' . $component . '...');
192 cron_trace_time_and_memory();
193 $pre_dbqueries = $DB->perf_get_queries();
194 $pre_time = microtime(true);
196 $cronfunction();
198 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
199 round(microtime(true) - $pre_time, 2) . " seconds)");
201 set_config('lastcron', time(), $component);
202 core_php_time_limit::raise();
205 if ($description) {
206 mtrace('Finished ' . $description);
211 * Used to add in old-style cron functions within plugins that have not been converted to the
212 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
213 * cron.php and some used a different name.)
215 * @param string $plugintype Plugin type e.g. 'report'
216 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
217 * 'report_frog_cron') for plugin cron functions that were already found using the new API
218 * @return array Revised version of $plugins that adds in any extra plugin functions found by
219 * looking in the older location
221 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
222 global $CFG; // mandatory in case it is referenced by include()d PHP script
224 if ($plugintype === 'report') {
225 // Admin reports only - not course report because course report was
226 // never implemented before, so doesn't need BC
227 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
228 $component = $plugintype . '_' . $pluginname;
229 if (isset($plugins[$component])) {
230 // We already have detected the function using the new API
231 continue;
233 if (!file_exists("$dir/cron.php")) {
234 // No old style cron file present
235 continue;
237 include_once("$dir/cron.php");
238 $cronfunction = $component . '_cron';
239 if (function_exists($cronfunction)) {
240 $plugins[$component] = $cronfunction;
241 } else {
242 debugging("Invalid legacy cron.php detected in $component, " .
243 "please use lib.php instead");
246 } else if (strpos($plugintype, 'grade') === 0) {
247 // Detect old style cron function names
248 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
249 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
250 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
251 $component = $plugintype.'_'.$pluginname;
252 if (isset($plugins[$component])) {
253 // We already have detected the function using the new API
254 continue;
256 if (!file_exists("$dir/lib.php")) {
257 continue;
259 include_once("$dir/lib.php");
260 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
261 $pluginname . '_cron';
262 if (function_exists($cronfunction)) {
263 $plugins[$component] = $cronfunction;
268 return $plugins;