Scheduled Tasks

An extension can run some of its routines periodically, for example, every 10 minutes, every hour, or daily. This scheduler interface manages the crontab utility on Linux and the Task Scheduler application on Windows. The interface is presented by two classes - pm_Scheduler and pm_Scheduler_Task. The first class represents a task manager and the second class represents a task.

To successfully schedule a task, your code must meet the following requirements:

Usage Examples

A sample code that adds a periodic task to the scheduler can look as follows:

$task = new pm_Scheduler_Task();
$task->setSchedule(array(
    'minute' => '0,4,9,14,19,24,29,34,39,44,49,54,59',
    'hour' => '*',
    'dom' => '*',
    'month' => '*',
    'dow' => '*'
    ));
$task->setCmd('five-minutes-task.php');
pm_Context::init('extension-id');
pm_Scheduler::getInstance()->putTask($task);  
var_dump($task->getId()); // Save task id in order to remove it if necessary

See an example of using scheduled tasks in Exercise 2.

Designing a Run Schedule

When designing a run schedule, you should pay attention to the following operating-system differences:

Listing Tasks

If you need to loop through scheduled tasks, do it in the following way:

$tasks = pm_Scheduler::getInstance()->listTasks();
foreach ($tasks as $task) {
    var_dump($task->getId());
    var_dump($task->getSchedule());
    var_dump($task->getCmd());
}
Removing Scheduled Tasks

We highly recommend that you save IDs of your scheduled tasks to the key-value storage and then remove the tasks during the removal of your extension. The following code removes a task:

$task = pm_Scheduler::getInstance()->getTaskById('64daef15d48e0fe038bb20a77a171150');
pm_Scheduler::getInstance()->removeTask($task);
Passing Arguments to Tasks

If you need to pass certain arguments to a task, use the setArguments method. The following code creates a task with arguments:

$task = new pm_Scheduler_Task();
$task->setSchedule(pm_Scheduler::$EVERY_DAY);
$task->setCmd('send-daily-report.php');
$task->setArguments(array('john', 'robert', 'ivan'));
pm_Scheduler::getInstance()->putTask($task);

To retrieve a task's arguments, use the getArguments method, for example, in the following way:

var_dump($task->getArguments());

 

Note that a task ID is assigned by the putTask method.