You are here

function search_api_cron in Search API 7

Same name and namespace in other branches
  1. 8 search_api.module \search_api_cron()

Implements hook_cron().

This will first execute any pending server tasks. After that, items will be indexed on all enabled indexes with a non-zero cron limit. Indexing will run for the time set in the search_api_index_worker_callback_runtime variable (defaulting to 15 seconds), but will at least index one batch of items on each index.

See also

search_api_server_tasks_check()

File

./search_api.module, line 340
Provides a flexible framework for implementing search services.

Code

function search_api_cron() {

  // Execute pending server tasks.
  search_api_server_tasks_check();

  // Load all enabled, not read-only indexes.
  $conditions = array(
    'enabled' => TRUE,
    'read_only' => 0,
  );
  $indexes = search_api_index_load_multiple(FALSE, $conditions);
  if (!$indexes) {
    return;
  }

  // Remember servers which threw an exception.
  $ignored_servers = array();

  // Continue indexing, one batch from each index, until the time is up, but at
  // least index one batch per index.
  $end = time() + variable_get('search_api_index_worker_callback_runtime', 15);
  $first_pass = TRUE;
  while (TRUE) {
    if (!$indexes) {
      break;
    }
    foreach ($indexes as $id => $index) {
      if (!$first_pass && time() >= $end) {
        break 2;
      }
      if (!empty($ignored_servers[$index->server])) {
        continue;
      }
      $limit = isset($index->options['cron_limit']) ? $index->options['cron_limit'] : SEARCH_API_DEFAULT_CRON_LIMIT;
      $num = 0;
      if ($limit) {
        try {
          $num = search_api_index_items($index, $limit);
          if ($num) {
            $variables = array(
              '@num' => $num,
              '%name' => $index->name,
            );
            watchdog('search_api', 'Indexed @num items for index %name.', $variables, WATCHDOG_INFO);
          }
        } catch (SearchApiException $e) {

          // Exceptions will probably be caused by the server in most cases.
          // Therefore, don't index for any index on this server.
          $ignored_servers[$index->server] = TRUE;
          $vars['%index'] = $index->name;
          watchdog_exception('search_api', $e, '%type while trying to index items on %index: !message in %function (line %line of %file).', $vars);
        }
      }
      if (!$num) {

        // Couldn't index any items => stop indexing for this index in this
        // cron run.
        unset($indexes[$id]);
      }
    }
    $first_pass = FALSE;
  }
}