MDL-50154 behat: Click on Grades link under navigation
[moodle.git] / lib / cronlib.php
blobcb8bb9882723029bb4c2204f75c29c8848e7abd8
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 (isset($predbqueries)) {
76 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
77 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
79 mtrace("Scheduled task complete: " . $task->get_name());
80 \core\task\manager::scheduled_task_complete($task);
81 } catch (Exception $e) {
82 if ($DB && $DB->is_transaction_started()) {
83 error_log('Database transaction aborted automatically in ' . get_class($task));
84 $DB->force_transaction_rollback();
86 if (isset($predbqueries)) {
87 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
88 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
90 mtrace("Scheduled task failed: " . $task->get_name() . "," . $e->getMessage());
91 \core\task\manager::scheduled_task_failed($task);
93 get_mailer('close');
94 unset($task);
97 // Run all adhoc tasks.
98 while (!\core\task\manager::static_caches_cleared_since($timenow) &&
99 $task = \core\task\manager::get_next_adhoc_task($timenow)) {
100 mtrace("Execute adhoc task: " . get_class($task));
101 cron_trace_time_and_memory();
102 $predbqueries = null;
103 $predbqueries = $DB->perf_get_queries();
104 $pretime = microtime(1);
105 try {
106 get_mailer('buffer');
107 $task->execute();
108 if (isset($predbqueries)) {
109 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
110 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
112 mtrace("Adhoc task complete: " . get_class($task));
113 \core\task\manager::adhoc_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("Adhoc task failed: " . get_class($task) . "," . $e->getMessage());
124 \core\task\manager::adhoc_task_failed($task);
126 get_mailer('close');
127 unset($task);
130 mtrace("Cron script completed correctly");
132 gc_collect_cycles();
133 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
134 $difftime = microtime_diff($starttime, microtime());
135 mtrace("Execution took ".$difftime." seconds");
139 * Output some standard information during cron runs. Specifically current time
140 * and memory usage. This method also does gc_collect_cycles() (before displaying
141 * memory usage) to try to help PHP manage memory better.
143 function cron_trace_time_and_memory() {
144 gc_collect_cycles();
145 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
149 * Executes cron functions for a specific type of plugin.
151 * @param string $plugintype Plugin type (e.g. 'report')
152 * @param string $description If specified, will display 'Starting (whatever)'
153 * and 'Finished (whatever)' lines, otherwise does not display
155 function cron_execute_plugin_type($plugintype, $description = null) {
156 global $DB;
158 // Get list from plugin => function for all plugins
159 $plugins = get_plugin_list_with_function($plugintype, 'cron');
161 // Modify list for backward compatibility (different files/names)
162 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
164 // Return if no plugins with cron function to process
165 if (!$plugins) {
166 return;
169 if ($description) {
170 mtrace('Starting '.$description);
173 foreach ($plugins as $component=>$cronfunction) {
174 $dir = core_component::get_component_directory($component);
176 // Get cron period if specified in version.php, otherwise assume every cron
177 $cronperiod = 0;
178 if (file_exists("$dir/version.php")) {
179 $plugin = new stdClass();
180 include("$dir/version.php");
181 if (isset($plugin->cron)) {
182 $cronperiod = $plugin->cron;
186 // Using last cron and cron period, don't run if it already ran recently
187 $lastcron = get_config($component, 'lastcron');
188 if ($cronperiod && $lastcron) {
189 if ($lastcron + $cronperiod > time()) {
190 // do not execute cron yet
191 continue;
195 mtrace('Processing cron function for ' . $component . '...');
196 cron_trace_time_and_memory();
197 $pre_dbqueries = $DB->perf_get_queries();
198 $pre_time = microtime(true);
200 $cronfunction();
202 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
203 round(microtime(true) - $pre_time, 2) . " seconds)");
205 set_config('lastcron', time(), $component);
206 core_php_time_limit::raise();
209 if ($description) {
210 mtrace('Finished ' . $description);
215 * Used to add in old-style cron functions within plugins that have not been converted to the
216 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
217 * cron.php and some used a different name.)
219 * @param string $plugintype Plugin type e.g. 'report'
220 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
221 * 'report_frog_cron') for plugin cron functions that were already found using the new API
222 * @return array Revised version of $plugins that adds in any extra plugin functions found by
223 * looking in the older location
225 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
226 global $CFG; // mandatory in case it is referenced by include()d PHP script
228 if ($plugintype === 'report') {
229 // Admin reports only - not course report because course report was
230 // never implemented before, so doesn't need BC
231 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
232 $component = $plugintype . '_' . $pluginname;
233 if (isset($plugins[$component])) {
234 // We already have detected the function using the new API
235 continue;
237 if (!file_exists("$dir/cron.php")) {
238 // No old style cron file present
239 continue;
241 include_once("$dir/cron.php");
242 $cronfunction = $component . '_cron';
243 if (function_exists($cronfunction)) {
244 $plugins[$component] = $cronfunction;
245 } else {
246 debugging("Invalid legacy cron.php detected in $component, " .
247 "please use lib.php instead");
250 } else if (strpos($plugintype, 'grade') === 0) {
251 // Detect old style cron function names
252 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
253 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
254 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
255 $component = $plugintype.'_'.$pluginname;
256 if (isset($plugins[$component])) {
257 // We already have detected the function using the new API
258 continue;
260 if (!file_exists("$dir/lib.php")) {
261 continue;
263 include_once("$dir/lib.php");
264 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
265 $pluginname . '_cron';
266 if (function_exists($cronfunction)) {
267 $plugins[$component] = $cronfunction;
272 return $plugins;