跳转到主要内容

转自自己的博客 :http://yuqingjiang.com/portfolio/?q=zh-hans/node/11

-----------------------------------

扯淡之前先放官方解释:

https://drupal.org/node/180528

然后是Drupal China的解释。

懒得翻译了 (我错了 有时间会翻译的)

 

直接解释案例吧。。因为之前写的是公司代码 不方便放出,直接用官网代码了

function batch_example($options1, $options2, $options3, $options4) { $batch = array(

    'operations' => array(

      array('batch_example_process', array($options1, $options2)),

      array('batch_example_process', array($options3, $options4)),

      ),

    'finished' => 'batch_example_finished',

    'title' => t('Processing Example Batch'),

    'init_message' => t('Example Batch is starting.'),

    'progress_message' => t('Processed @current out of @total.'),

    'error_message' => t('Example Batch has encountered an error.'),

    'file' => drupal_get_path('module', 'batch_example') . '/batch_example.inc',

  );

  batch_set($batch);

  batch_process('node/1');

}

function batch_example_process($options1, $options2, &$context) {

  if (!isset($context['sandbox']['progress'])) {

    $context['sandbox']['progress'] = 0;

    $context['sandbox']['current_node'] = 0;

    $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();

  }

 

  $limit = 5;

 

  $result = db_query_range("SELECT nid FROM {node} WHERE nid > %d ORDER BY nid ASC", $context['sandbox']['current_node'], 0, $limit);

  while ($row = db_fetch_array($result)) {

 

    $node = node_load($row['nid'], NULL, TRUE);

    $node->value1 = $options1;

    $node->value2 = $options2;

    node_save($node);

 

    // Store some result for post-processing in the finished callback.

    $context['results'][] = check_plain($node->title);

 

    $context['sandbox']['progress']++;

    $context['sandbox']['current_node'] = $node->nid;

    $context['message'] = t('Now processing %node', array('%node' => $node->title));

  }

 

  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {

    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];

  }

}

function batch_example_finished($success, $results, $operations) {

  if ($success) {

    $message = count($results) .' processed.';

    $message .= theme('item_list', $results);  

    drupal_set_message($message);

  }

  else {

    $error_operation = reset($operations);

    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));

    drupal_set_message($message, 'error');

  }

}