我一直在成功地使用批处理 API 进行通常会导致 PHP 超时或内存不足错误的处理,并且它运行良好。
我已经浏览了一些代码,但我仍然不清楚幕后发生了什么。
熟悉该过程的人可以描述它是如何工作的吗?
我一直在成功地使用批处理 API 进行通常会导致 PHP 超时或内存不足错误的处理,并且它运行良好。
我已经浏览了一些代码,但我仍然不清楚幕后发生了什么。
熟悉该过程的人可以描述它是如何工作的吗?
我已经浏览了一些代码,但我仍然不清楚幕后发生了什么。
熟悉该过程的人可以描述它是如何工作的吗?
发生的情况是,为避免 PHP 超时,浏览器会定期通过 AJAX ping导致执行批处理操作的 URL ( http://example.com/batch?id= $id)。
请参阅_batch_page(),这是system_batch_page()调用的函数,是“批处理”路径的菜单回调。
function _batch_page() {
$batch = &batch_get();
// Retrieve the current state of batch from db.
if (isset($_REQUEST['id']) && $data = db_result(db_query("SELECT batch FROM {batch} WHERE bid = %d AND token = '%s'", $_REQUEST['id'], drupal_get_token($_REQUEST['id'])))) {
$batch = unserialize($data);
}
else {
return FALSE;
}
// Register database update for end of processing.
register_shutdown_function('_batch_shutdown');
$op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
$output = NULL;
switch ($op) {
case 'start':
$output = _batch_start();
break;
case 'do':
// JS-version AJAX callback.
_batch_do();
break;
case 'do_nojs':
// Non-JS progress page.
$output = _batch_progress_page_nojs();
break;
case 'finished':
$output = _batch_finished();
break;
}
return $output;
}
在_batch_progress_page_nojs()中,您会注意到以下代码。
$url = url($batch['url'], array('query' => array('id' => $batch['id'], 'op' => $new_op)));
drupal_set_html_head('<meta http-equiv="Refresh" content="0; URL=' . $url . '">');
$output = theme('progress_bar', $percentage, $message);
return $output;
设置“刷新”元标记将导致页面刷新。
Drupal 7 中有类似的代码;不同之处在于代码已被移植,并且它使用了 Drupal 7 实现的新功能。
// Merge required query parameters for batch processing into those provided by
// batch_set() or hook_batch_alter().
$batch['url_options']['query']['id'] = $batch['id'];
$batch['url_options']['query']['op'] = $new_op;
$url = url($batch['url'], $batch['url_options']);
$element = array(
'#tag' => 'meta',
'#attributes' => array(
'http-equiv' => 'Refresh',
'content' => '0; URL=' . $url,
),
);
drupal_add_html_head($element, 'batch_progress_meta_refresh');
return theme('progress_bar', array('percent' => $percentage, 'message' => $message));
启用 JavaScript 后,完成所有工作的代码位于batch.js文件中。
/**
* Attaches the batch behavior to progress bars.
*/
Drupal.behaviors.batch = function (context) {
// This behavior attaches by ID, so is only valid once on a page.
if ($('#progress.batch-processed').size()) {
return;
}
$('#progress', context).addClass('batch-processed').each(function () {
var holder = this;
var uri = Drupal.settings.batch.uri;
var initMessage = Drupal.settings.batch.initMessage;
var errorMessage = Drupal.settings.batch.errorMessage;
// Success: redirect to the summary.
var updateCallback = function (progress, status, pb) {
if (progress == 100) {
pb.stopMonitoring();
window.location = uri+'&op=finished';
}
};
var errorCallback = function (pb) {
var div = document.createElement('p');
div.className = 'error';
$(div).html(errorMessage);
$(holder).prepend(div);
$('#wait').hide();
};
var progress = new Drupal.progressBar('updateprogress', updateCallback, "POST", errorCallback);
progress.setProgress(-1, initMessage);
$(holder).append(progress.element);
progress.startMonitoring(uri+'&op=do', 10);
});
};
批处理 URL 的轮询以progress.startMonitoring(uri+'&op=do', 10)
. batch.js 文件依赖于在progress.jsDrupal.progressBar
文件中定义的功能。
Drupal 7 中使用了类似的代码,它使用了稍微不同版本的batch.js和progress.js文件。
(function ($) {
/**
* Attaches the batch behavior to progress bars.
*/
Drupal.behaviors.batch = {
attach: function (context, settings) {
$('#progress', context).once('batch', function () {
var holder = $(this);
// Success: redirect to the summary.
var updateCallback = function (progress, status, pb) {
if (progress == 100) {
pb.stopMonitoring();
window.location = settings.batch.uri + '&op=finished';
}
};
var errorCallback = function (pb) {
holder.prepend($('<p class="error"></p>').html(settings.batch.errorMessage));
$('#wait').hide();
};
var progress = new Drupal.progressBar('updateprogress', updateCallback, 'POST', errorCallback);
progress.setProgress(-1, settings.batch.initMessage);
holder.append(progress.element);
progress.startMonitoring(settings.batch.uri + '&op=do', 10);
});
}
};
})(jQuery);
不同之处在于,从 Drupal 7 开始,所有 jQuery 代码都包含在 中(function ($) { })(jQuery);
,并且jQuery Once 插件包含在 Drupal 7中。Drupal 7 还设置了与屏幕阅读器兼容的 WAI-ARIA 属性;这也发生在从 JavaScript 代码添加的 HTML 中,例如在 progress.js 文件中找到的以下内容。
// The WAI-ARIA setting aria-live="polite" will announce changes after users
// have completed their current activity and not interrupt the screen reader.
this.element = $('<div class="progress" aria-live="polite"></div>').attr('id', id);
this.element.html('<div class="bar"><div class="filled"></div></div>' +
'<div class="percentage"></div>' +
'<div class="message"> </div>');
当为批处理页面提供服务时,Drupal 将_batch_shutdown()设置为关闭回调;当 PHP 因为超时而关闭时,该函数会更新数据库中的批处理数组。
// Drupal 6.
function _batch_shutdown() {
if ($batch = batch_get()) {
db_query("UPDATE {batch} SET batch = '%s' WHERE bid = %d", serialize($batch), $batch['id']);
}
}
// Drupal 7.
function _batch_shutdown() {
if ($batch = batch_get()) {
db_update('batch')
->fields(array('batch' => serialize($batch)))
->condition('bid', $batch['id'])
->execute();
}
}
从一个很好的示例实现:
每个批处理操作回调将一遍又一遍地迭代,直到 $context['finished'] 设置为 1。每次通过后,batch.inc 将检查其计时器并查看是否到了新的 http 请求的时间,即何时超过 1自上次请求以来已过去一分钟。
一个处理速度非常快的整个批次可能只需要一个 http 请求,即使它迭代了几次回调,而较慢的进程可能会在每次回调迭代时启动一个新的 http 请求。
这意味着您应该将您的处理设置为在每次迭代中尽可能多地完成,而无需 php 超时,然后让 batch.inc 决定是否需要发出新的 http 请求。
换句话说:您必须将您的一批任务分成块(或单个任务),这样才不会超时。如果发现 PHP 超时临近,Drupal 将结束当前调用并打开一个新的 HTTP 请求。