Scheduled tasks
Scheduled tasks are tasks that will run on a regular schedule. A default schedule can be set, but administrators have the ability to change the default schedule if required.
Tasks will only run as often as cron is run in Moodle. It is recommended that cron be run at least once per minute to get the most benefit from the task scheduling.
Creating scheduled tasks
To create a new scheduled task and set its default configuration you should:
- create a new class which extends the
\core\task\scheduled_task
class; - create an entry for your scheduled task in the
db/tasks.php
file within your plugin; and - increment the version number for your plugin.
Task class
The class for your scheduled task, which extends the \core\task\scheduled_task
class, should be in the classes/task
directory of your plugin.
View example scheduled task
db/tasks.php
Task schedule configuration
File path: /db/tasks.php
The db/tasks.php
file contains the initial schedule configuration for each of your plugins scheduled tasks. Adhoc tasks are not run on a regular schedule and therefore are not described in this file.
If an existing task is edited, it will only be updated in the database if the administrator has not customised the schedule of that task in any way.
The following fields also accept a value of R
, which indicates that Moodle should choose a random value for that field:
- minute
- hour
- dayofweek
- day
See db/tasks.php for full details of the file format.
View example
Running tasks for disabled plugins
In rare cases, you may want the scheduled tasks for a plugin to run, even when the plugin is disabled. One example use-case is in Enrolment plugins where a disabled plugin must still clear up data.
To support this, your scheduled task must override the get_run_if_component_disabled()
method to return true
.
Debugging
When called from the command line for testing purposes errors can be hidden and a misleading error about locks can be displayed. You can view more information of the error using the --showdebugging
parameter when calling the scheduled task from the CLI.