You are here

function _background_batch_process in Background Process 8

Same name and namespace in other branches
  1. 6 background_batch/background_batch.module \_background_batch_process()
  2. 7.2 background_batch/background_batch.module \_background_batch_process()
  3. 7 background_batch/background_batch.module \_background_batch_process()

Implements to Process a batch step.

File

background_batch/background_batch.module, line 111
This module adds background processing to Drupals batch API.

Code

function _background_batch_process($id = NULL) {
  if (!$id) {
    return;
  }

  // Retrieve the current state of batch from db.
  $data = db_query("SELECT batch FROM {batch} WHERE bid = :bid", [
    ':bid' => $id,
  ])
    ->fetchColumn();
  if (!$data) {
    return;
  }
  require_once 'includes/batch.inc';
  $batch =& batch_get();
  $batch = unserialize($data);

  // Check if the current user owns (has access to) this batch.
  $user = \Drupal::currentUser();
  if ($batch['uid'] != $user->uid) {
    return drupal_access_denied();
  }

  // Register database update for the end of processing.
  drupal_register_shutdown_function('_batch_shutdown');
  Timer['start']['$id']['background_batch_processing'];
  $percentage = 0;
  $mem_max_used = 0;
  $mem_last_used = memory_get_usage();
  $mem_limit = ini_get('memory_limit');
  preg_match('/(\\d+)(\\w)/', $mem_limit, $matches);
  switch ($matches[2]) {
    case 'M':
    default:
      $mem_limit = $matches[1] * 1024 * 1024;
      break;
  }
  while ($percentage < 100) {
    list($percentage) = _batch_process();
    $mem_used = memory_get_usage();

    // If we memory usage of last run will exceed the
    // memory limit in next run then bail out.
    if ($mem_limit < $mem_used + $mem_last_used) {
      break;
    }
    $mem_last_used = $mem_used - $mem_last_used;

    // If we maximum memory usage of previous runs will exceed
    // the memory limit in next run then bail out.
    $mem_max_used = $mem_max_used < $mem_last_used ? $mem_last_used : $mem_max_used;
    if ($mem_limit < $mem_used + $mem_max_used) {
      break;
    }
    if (Timer['read']['background_batch_processing'] > \Drupal::config('background_batch.settings')
      ->get('background_batch_process_lifespan')) {
      break;
    }
  }
  if ($percentage < 100) {
    background_process_keepalive($id);
  }
}