I'm trying to send an email during the scheduled task of a module I'm building and continue to get an error:
Coding problem: $PAGE->context was not set. You may have forgotten to call require_login() or $PAGE->set_context(). The page may not display correctly as a result
- line 493 of /lib/pagelib.php: call to debugging()
- line 820 of /lib/pagelib.php: call to moodle_page->magic_get_context()
- line 1432 of /lib/weblib.php: call to moodle_page->__get()
- line 5878 of /lib/moodlelib.php: call to format_string()
- line 58 of /mod/ojt/classes/task/notify.php: call to email_to_user()
- line 105 of /lib/cronlib.php: call to mod_ojt\task\notify->execute()
- line 297 of /lib/cronlib.php: call to cron_run_inner_scheduled_task()
- line 91 of /admin/tool/task/schedule_task.php: call to cron_run_single_task()
I've looked at other plugins and can't figure out what's wrong. This is running as a scheduled task so I'm confused why I need to set the context for the page. Could someone offer some advice on what I'm doing wrong?
My code looks like this:
namespace mod_ojt\task;
defined('MOODLE_INTERNAL') || die();
class notify extends \core\task\scheduled_task {
public function get_name() {
// Shown in admin screens
return get_string('notifytask', 'mod_ojt');
}
public function execute() {
global $DB, $CFG, $PAGE, $SITE;
require_once($CFG->dirroot . '/config.php');
$toUserId = 2;
$toUser = $DB->get_record('user', array('id' => $toUserId));
$fromUserId = 5;
$fromUser = $DB->get_record('user', array('id' => $fromUserId));
$subject = "OJT Approval Needed";
$messageText = "Test";
$messageHtml = "Test";
email_to_user($toUser, $fromUser, $subject, $messageText, $messageHtml);
}
} // end of class notify