phpcronmoodlemoodle-api

Adding a cronjob with moodle-cron-api is not working properly


I am trying to schedule a task in moodle-cron-api following the instructions here at: https://docs.moodle.org/dev/Task_API.

I have the root folder at /local and the name of the root folder is mod_hygene.

I have a cut_my_toe_nails.php at /local/mod_hygene/classes/task which is:

namespace mod_hygene\task;

/**
* An example of a scheduled task.
*/
class cut_my_toe_nails extends \core\task\scheduled_task {

/**
* Return the task's name as shown in admin screens.
*
* @return string
*/
public function get_name() {
return get_string('cutmytoenails', 'mod_hygene');
}

/**
* Execute the task.
*/
public function execute() {
// Apply fungus cream.
// Apply chainsaw.
// Apply olive oil.
echo 'do';
}
}

And there is /mod_hygene/db/tasks.php:

$tasks = [
[
'classname' => 'mod_hygene\task\cut_my_toe_nails',
'blocking' => 0,
'minute' => '*',
'hour' => '*',
'day' => '*',
'month' => '1,7',
'dayofweek' => '*',
],
];

As you see, the task should run every minute. I run my moodle container via terminal with

docker-compose up -d --build moodle

In the terminal I should see 'do' printed every minute. But, I am not seeing anything. I hovered to Site Administration/Server/Scheduled Tasks. There I am not seeing this task. But I checked in Site Administration/Plugins/Plugins Overview and could find local_mod_hygene in the Local Plugins.

Can anyone help me with it? Do I need to make some changes to the Dockerfile as well?


Solution

  • Just a tip, don't use the prefix mod_ for a local plugin, it could be confused for an activity plugin in the mod folder.

    So assuming your code is in /local/hygene/

    The task file should be /local/hygene/classes/task/cut_my_toe_nails.php

    The class namespace should be

    namespace local_hygene\task;
    

    The tasks file should be /local/hygene/db/tasks.php with

    'classname' => 'local_hygene\task\cut_my_toe_nails',
    

    Once its installed, check if the task is enabled via

    Site admin > Server > Tasks

    Or direct to

    yourwebsite/admin/tool/task/scheduledtasks.php

    If its installed and enabled, then run it from the command line to test it.

    First see if its listed - if its not listed then its not installed correctly

    php admin/cli/scheduled_task.php  --list
    

    If it it listed, then note the name and run the task manually - note that the \ has to be escaped with \\

    php admin/cli/scheduled_task.php --execute=\\local_hygene\\task\\cut_my_toe_nails
    

    If the task is working correctly, then wait for cron

    Or, depending on the settings, you can run cron manually via yourmoodlewebsite/admin/cron.php when logged in as an admin

    Or from the command line

    php admin/cli/cron.php