Task Scheduler for Developers: Writing Your Own Task

A task is a model class in a fixed folder. Task Scheduler finds it automatically: it appears in the Module list of the task form, and the scheduler calls it by schedule. The bundled tasks (sample_task.php, test_multi_step.php, request_url.php, download_file.php) are working examples.

File, namespace and class

  • File: admin/model/extension/ka_extensions/tasks/<task_name>.php, for example my_export.php.
  • Namespace: extension\ka_extensions\tasks.
  • Class: Model + the file name without underscores, for example ModelMyExport. It extends \KaModel.
  • Add the full class name alias, as in all bundled tasks.
  • The class must have the runSchedulerOperation() method. A file without it is not shown in the Module list.
  • Task models are loaded through the Ka Extensions loader, so they can be extended with KaMod like other Ka models.
PHP
<?php
namespace extension\ka_extensions\tasks;

class ModelMyExport extends \KaModel {

    public function runSchedulerOperation($operation, $params, &$stat) {
        $stat = array('Exported products' => 10);
        return 'finished';
    }
}

class_alias(__NAMESPACE__ . '\ModelMyExport', 'ModelExtensionKaExtensionsTasksMyExport');

Methods

Method Required Purpose
runSchedulerOperation($operation, $params, &$stat) yes Does the work (one step). $operation is the operation code, $params the saved parameter values, $stat the results to show.
getModuleName() no Readable name shown in brackets after the file name in the Module list.
requestSchedulerOperations() no Operations of the task: array('code' => 'Title'). Without it the form skips the Operation step.
requestSchedulerOperationParams($operation) no Parameter fields of the operation (see below).
stopSchedulerOperation($operation) no Called when a running task is stopped: Stop button, time or failure limit. Remove temporary files or other data of the unfinished run here.

Parameter fields:

PHP
public function requestSchedulerOperationParams($operation) {
    return array(
        'file' => array(
            'title'    => 'File name',
            'type'     => 'text',      // text, password or select
            'required' => true,
            'descr'    => 'Example: export/products.csv',  // tooltip, optional
        ),
        'format' => array(
            'title'    => 'Format',
            'type'     => 'select',
            'options'  => array('csv' => 'CSV', 'xml' => 'XML'),
            'required' => false,
        ),
    );
}

The values are saved with the task and passed to runSchedulerOperation() as $params['file'], $params['format'].

Results

runSchedulerOperation() returns one of:

  • 'finished': the task is complete. The completion counter grows, the failure counter is reset, the email is sent if enabled.
  • 'not_finished': the step is done, the task needs more steps. The scheduler calls it again at once (HTTP redirect, or a loop in the command line).
  • array('result' => 'finished', 'next_task_id' => N): the task is complete and task N runs right after it, even if task N is not active or not due.

Any other value stops the task. It is logged as "ERROR: Unknown function result" and not counted as completed.

$stat is an array of label => value pairs. It is shown on the Task Statistics page and in the completion email. Keep the values short strings or numbers.

Multi-step tasks

Split long work (imports, exports, mass updates) into steps:

  • Keep the state between steps in $this->session->data. The scheduler saves the session after a 'not_finished' step and restores it before the next step. After 'finished' the saved session is cleared.
  • Use key names unique to your task (for example my_export_offset), and set them on the first step: the session of the first step may already contain other data.
  • Keep one step well below the "Treat Task As Dead" time (default 5 minutes) and the PHP time limit of the server. A step that runs longer is treated as dead and continued by the next call.
  • The whole run must finish within "Stop Task After 'N' Minutes Activity" (default 30 minutes).
  • Do not make very short steps: a task that makes 10 or more steps within the first 60 seconds is stopped as a runaway task.
  • Do not let tasks call each other in a loop with next_task_id.

Example:

PHP
public function runSchedulerOperation($operation, $params, &$stat) {

    if (!isset($this->session->data['my_export_offset'])) {   // first step
        $this->session->data['my_export_offset'] = 0;
    }
    $offset = $this->session->data['my_export_offset'];

    $done = $this->exportProducts($params, $offset, 500);    // your code, returns the number of exported rows
    $this->session->data['my_export_offset'] = $offset + $done;

    $stat = array('Exported products' => $offset + $done);

    if ($done == 500) {
        return 'not_finished';
    }

    unset($this->session->data['my_export_offset']);
    return 'finished';
}

public function stopSchedulerOperation($operation) {
    // remove temporary files, locks and other data of an unfinished run
}

After a stop the saved session of the task is not used: the next run starts from the first step.

Shipping a task with your module

Put the task model into your module package. To create a ready task when your module is installed, use the Task Scheduler model in the installer of your module:

PHP
public function install() {
    if (!\extension\ka_extensions\KaGlobal::isKaInstalled('ka_scheduler', true)) {
        // Task Scheduler is not installed: show a message to the user
        return false;
    }
    if (!parent::install()) {
        return false;
    }

    $ka_tasks = $this->load->kamodel('extension/ka_extensions/ka_scheduler/ka_tasks');

    // add the task once, the user may have changed its schedule
    if (!$ka_tasks->enumTasks('my_export')) {
        $ka_tasks->installTask(array(
            'name'           => 'Export products',
            'module'         => 'my_export',        // task file name
            'operation'      => '',                 // operation code, if the task has operations
            'params'         => array(),
            'period_type'    => 'day',              // every_n_minutes, hour, day, week, month, year
            'period_at_hour' => 3,
            'period_at_min'  => 0,
            'start_at'       => date('Y-m-d 03:00:00'),
            'active'         => 'Y',
            'priority'       => 0,
        ));
    }
    return true;
}

public function uninstall() {
    if (\extension\ka_extensions\KaGlobal::isKaInstalled('ka_scheduler', true)) {
        $ka_tasks = $this->load->kamodel('extension/ka_extensions/ka_scheduler/ka_tasks');
        foreach ($ka_tasks->enumTasks('my_export') as $task) {
            $ka_tasks->uninstallTask($task['task_id']);
        }
    }
    return true;
}
  • enumTasks($module) returns the tasks of a task file.
  • installTask($task, $replace = false) adds a task. With $replace = true it first deletes all tasks of the same module. Tasks added this way have no end date. Add 'is_send_email' => 1 to send the completion email.
  • uninstallTask($task_id) deletes a task.

Tasks added this way also run in the free Lite version, where users cannot create tasks by hand.