我一直在成功使用Batch API进行处理,这通常会导致PHP超时或内存不足错误,并且它运行良好。
我仔细查看了代码,但我仍然不清楚幕后发生了什么。
熟悉该过程的人是否可以描述它的工作原理?
答案 0 :(得分:5)
我仔细查看了代码,但我仍然不清楚幕后发生了什么。
熟悉该过程的人是否可以描述它的工作原理?
为了避免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);
});
};
批处理网址的轮询以progress.startMonitoring(uri+'&op=do', 10)
开头。 batch.js文件取决于Drupal.progressBar
中公开的功能,该功能在progress.js文件中定义。
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 plugin is included with 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();
}
}
答案 1 :(得分:1)
来自great example implementation:
每个批处理操作回调将反复迭代直到 $ context ['finished']设置为1. 每次传递后,batch.inc将会 检查它的计时器,看看是否是新的http请求的时间, 即自上次请求后超过1分钟时。
处理速度非常快的整批产品可能只需要一个 http请求,即使它多次遍历回调, 较慢的进程可能会在每个进程上发起新的http请求 迭代的回调。
这意味着您应该将处理设置为在每次迭代中完成 只有在没有php超时的情况下才能做到这一点,然后让batch.inc 决定是否需要发出新的http请求。
换句话说:您必须将您的一批任务拆分成块(或单个任务),而不会超时。如果看到PHP超时接近,Drupal将结束其currrent调用并打开一个新的HTTP请求。