class MyModule extends Module {
...
public function install() {
// Perform install logic, such as installing cron tasks
Loader::loadModels($this, ['CronTasks']);
// Retrieve the cron task if it already exists for another company
$task = $this->CronTasks->getByKey('task_one', 'my_module', 'module');
if (!$task) {
// Create the automation task
$task = [
'key' => 'task_one', // a string used to identify this cron task (see MyPluginPlugin::cron())
'task_type' => 'module', // this cron task is for a module, so it must be set to 'module'
'dir' => 'my_module', // the directory of this module
'name' => 'My Module Task', // the name of this cron task
'description' => 'This cron tasks does stuff', // the description of this task
'type' => 'time' // "time" = once per day at a defined time, "interval" = every few minutes or hours
];
$task_id = $this->CronTasks->add($task);
} else {
$task_id = $task->id;
}
// Create the cron task run for this company
if ($task_id) {
$task_run = array(
'time' => '14:25', // the daily 24-hour time that this task should run (optional, required if interval is not given)
// 'interval' => '15', // the interval, in minutes, that this cron task should run (optional, required if time is not given)
'enabled' => 1, // 1 if this cron task is enabled, 0 otherwise (optional, default 1)
);
$this->CronTasks->addTaskRun($task_id, $task_run);
}
}
public function upgrade($current_version) {
// Perform upgrade logic
}
public function uninstall($module_id, $last_instance) {
// Perform uninstall logic, such as deleting cron tasks
Loader::loadModels($this, ['CronTasks']);
// Retrieve the cron task run for this company
$cron_task_run = $this->CronTasks->getTaskRunByKey('task_one', 'my_module', false, 'module');
if ($last_instance) {
// Delete all trace of this module, such as cron tasks
// Remove the cron task altogether
$cron_task = $this->CronTasks->getByKey('task_one', 'my_module', 'module');
if ($cron_task) {
$this->CronTasks->deleteTask($cron_task->id, 'module', 'my_module');
}
}
// Remove individual task run
if ($cron_task_run) {
$this->CronTasks->deleteTaskRun($cron_task_run->task_run_id);
}
}
...
}
|