Moodle | How to create a scheduled task in moodle

|
| By Webner

In moodle we can create scheduled tasks which will run after a defined interval. We also have cron jobs in moodle but they usually run after every minute so if we need to run a task after a particular time we need to create a scheduled task for this.

An administrator can schedule the task from front end by navigating through administration:>site administration->server->scheduled tasks,

We will be redirected to admin/tool/task/scheduledtasks.php.

On this page we have the list of scheduled tasks. We can edit any task, change its time or we can also disable it if it is no longer needed.

Suppose we want to create a task to send an email after every 15 mins with some output in quiz type plugin called test. We can name our task – send_email.

To create a scheduled task we need to create three files:

1. In the plugin, create a file “tasks.php” in DB folder. In tasks.php write the following code:

<?php
defined('MOODLE_INTERNAL') || die();
$tasks = array(  
array(
     'classname' => 'quiz_test\task\send_email, 
     'blocking' => 0
     'minute' => '*/15',       //run after every 15 mins
     'hour' => '*'
     'day' => '*'
     'dayofweek' => '*', 
     'month' => '*'
)
);
?>

2. Now Create a subclass of \core\task\scheduled_task that contains the code to run in a schedule (within “test/classes/task/send_email.php” for the autoloading mechanism to pick up):

<?php
namespace quiz_test\task;
class send_email extends \core\task\scheduled_task { 
public function get_name() {
     // Shown on admin screens
    return get_string('email_send', 'quiz_test'); //get the string from lang/en/ 
}

public function execute() {  
      global $CFG;
     require_once($CFG->dirroot . '/quiz/test/lib.php');
      quiz_test_email(); //function to execute
}
}
?>

3. Now give definition to the function in lib.php of the plugin:

<?php
defined('MOODLE_INTERNAL') || die;
function quiz_test_email ()
{           
 $email_user1 = new stdClass;
$email_user1>email= "abc@example.com";
$email_user1>firstname=" ";
$email_user1>lastname;
$email_user1>maildisplay = true;
$email_user1>mailformat = 1; // 0 (zero) text-only emails, 1 (one) for HTML/Text emails.
$email_user1>id=-99;
$a= email_to_user($email_user, $email_user1, $subject, $content);
}
?>

After writing this code we will be able to see our tasks page: (/admin/tool/task/scheduledtasks.php):

301

We can edit the task by clicking on pencil icon:

302

We can change the time-frequency and can also disable the task according to needs and can also set it to default. It will take default value from tasks.php:

Leave a Reply

Your email address will not be published. Required fields are marked *