Batch Jobs usage
Batch Jobs uses a class for creating and modifying (add to) a batch job. Typical code for creating a batch job would look something like:
global $user;
$batch_title = 'My batch title';
module_load_include('inc', 'batch_jobs', 'BatchJob');
$batch = new BatchJob($batch_title, $user->uid);
Include the user ID if you want the batch job to belong to a user and not be accessible to other users with the 'access batch jobs' permission.
Function callbacks to be run when the batch job is completed can be added using:
$batch->addBatchCallbacks(array('my_completion_callback'));
Parameters to be passed to the above callbacks or all task functions are global parameters. These can be added to a batch using:
$global_params = array(
'global_arg1' => $global_arg1,
'global_arg2' => $global_arg2,
);
$batch->addBatchParams($global_params);
A task can have it's own callbacks and parameters. To create a task:
$task_title = 'My task title';
$functions = array(
'my_task_callback',
);
$task_params = array(
'task_arg1' => $task_arg1,
'task_arg2' => $task_arg2,
);
$batch->addTask($task_title, $functions, $task_params);
Task arguments that are keyed the same as global arguments will replace the global arguments. This allows tasks to override the global parameters.
The function signature for callbacks is (example assumes the task is creating a node)
function my_task_callback($params) {
...
$node = ...
$results = new stdClass;
$results->status = TRUE;
$results->message = array('nid' => $node->nid);
return $results;
Set $results->status to false if the task fails. Anything in $results->message will be stored in the task table in the database and displayed in the task reports.
The batch jobs accessible by the current user are in the administration menus and can be found at admin/reports/batch_jobs. From that page the job can be run one task at a time (useful for debugging) or the whole job at once.
Running batch jobs in Drupal 8 using cron or drush after the batch job has been created would look something like
$job = new Job($batch_id);
$ran = $job->run()
$job->finish();
To limit the load on the server, pass the number of tasks to run in the run() method. This can be done periodically using cron. If the return $ran is zero then there are no tasks left to be run and the finish() method can be called.
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion