Question

Currently, I have a batch process that is triggered on a form submit.

With more detail, I have something like this:

function mymodule_form_submit($form, &$form_state) {
  // call some functions

  $number_of_sets = 5;

  $batch = array(
    'title' => t('Getting data...'),
      'operations' => array(),
      'finished' => 'mymodule_batch_finished',
      'init_message' => t('Starting ...'),
      'progress_message' => t('Processed @current out of @total.'),
      'error_message' => t('An error occurred during processing'),
      'progressive' => TRUE
    );

  foreach (range(0, $number_of_sets - 1) as $i) {
    $batch['operations'][] = array('mymodule_batch', array($cookie, $var1, $var2));
  }     
  batch_set($batch);

  // call a final function
}

This works fine trough the GUI, i.e., manually submiting the form.

But I need to have the possibility to schedule this batch operation or, more correctly, I need to schedule all the code in that form submit.

This is what I've tried:

function mymodule_cronapi($op, $job = NULL) {
    $items['Import Data'] = array(
        'description' => 'Import Data',
        'rule' => '0 * * * *', // every hour
        'callback' => 'mymodule_proccessdata',
    );
    return $items;
}

function mymodule_proccessdata() {
  // call some functions

  $number_of_sets = 5;

  $batch = array(
    'title' => t('Getting data...'),
      'operations' => array(),
      'finished' => 'mymodule_batch_finished',
      'init_message' => t('Starting ...'),
      'progress_message' => t('Processed @current out of @total.'),
      'error_message' => t('An error occurred during processing'),
      'progressive' => TRUE
    );

  foreach (range(0, $number_of_sets - 1) as $i) {
    $batch['operations'][] = array('mymodule_batch', array($cookie, $var1, $var2));
  }     
  batch_set($batch);

  // call a final function
}

So, basically, I call the same code in the form submit in the hook_cronapi. Everything works fine except for the batch operation.

So, it is not possible to call a batch operation with cron?

I've read about using drupal queue but I'm really lost on how to adapt the code I have and I'm concerned that using queue will just schedule the operation and not do it at the precise time, like it's done with the submit.

Any toughts?

EDIT: I tried queue with no success. See below.

function mymodule_cron_queue_info() {
  $queues = array(
    'dothings' => array(
      'worker callback' => 'mymodule_proccessdata',
      'time' => 60*30,
    ),
  );
  return $queues;
}

function mymodule_cron() {
  $import_item = DrupalQueue::get('dothings');
  $import_item->createItem(array());
}
Was it helpful?

Solution

Check with drupal_is_cli() if you are running from command line.

If yes, just fire the entire process instead, no need for batch-api as there will be no timeouts.

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top