I am developing a block, which makes use of scheduled tasks. The ’scheduled task’ part works just fine, as in it fires off when needed, shows up in the list of scheduled tasks and can be edited by the site’s admin.
The part I am struggling with is calling functions from within the ‘public function execute()’, like it is done in the forum implementation of cron (see /mod/forum/classes/task/cron_task.php, as below)
namespace mod_forum\task;
class cron_task extends \core\task\scheduled_task {
/**
* Get a descriptive name for this task (shown to admins).
*
* @return string
*/
public function get_name() {
return get_string('crontask', 'mod_forum');
}
/**
* Run forum cron.
*/
public function execute() {
global $CFG;
require_once($CFG->dirroot . '/mod/forum/lib.php');
forum_cron(); // function is being called here, and works fine
}
}
Here is what my blocks/block_broken_links/classes/task/cron_task.php file looks like. When I run /admin/cron.php manually, it returns a fatal error stating it cannot find the broken_links_cron function.
namespace block_broken_links\task;
class cron_task extends \core\task\scheduled_task {
/**
* Get a descriptive name for this task (shown to admins).
*
* @return string
*/
public function get_name() {
return get_string('crontask', 'block_broken_links');
}
/**
* Run broken links cron.
*/
public function execute() {
global $CFG;
require_once($CFG->dirroot . ‘/blocks/block_broken_links/block_broken_links.php');
broken_links_cron(); //<— function is being called here, fatal error is returned
}
}
It is worth noting that:
- When I replace the function call (broken_links_cron) with the actual code from that function, /admin/cron.php works fine and returns no error.
- When I run the broken_links_cron from another file (completely bypassing the scheduled tasks and cron mechanisms), it works fine
- Other modules, or parts of Moodle, call functions from within the ‘public function execute()’ part of the cron_task.php files with no problems (e.g. badges)
What I am doing wrong? Should I namespace my block_broken_links.php file? Would that break anything? Am I missing something obvious? Is what I am trying to do impossible with non-core code? Any help would be appreciated
Cheers,
Fred