0

I wanted a way to only insert items into the Queue when it was not already added. I want to have a large queue and work my way through it, simply adding as required. Previously I was deleting the queue and recreating on a set time table.

I couldn't find any way of doing this, or any discussion other than 'it's not possible.

I created the method below. I have not used it for huge queues yet, but I post it here in the hope that better options if available might get posted too.

1 Answer 1

1

Create a class to extend the systemqueue. I called mine Unique. This will serialise the data use db_merge to insert only if it doesn't exist.

class Unique extends SystemQueue {

  public function createItem($data) {

    // save doing this twice
    $serial_data = serialize($data);

    // ignoring expire
    $query = db_merge('queue')
    ->key(array('name' => $this->name, 'data' => $serial_data))
    ->fields(array(
        'name' => $this->name,
        'data' => $serial_data,
        'created' => time(),
    ));
    return (bool) $query->execute();
  }
}

You then add the variables to hook_install() or hook_enable().

variable_set('queue_class_[your queue name]', 'Unique');

matching [your queue name] to the queue name, e.g if you used this:

DrupalQueue::get('update_profile_tasks')->createQueue();

the variable would be:

variable_set('queue_class_update_profile_tasks', 'Unique');

Thanks to this for getting me on track. Updated answer to be cleaner thanks to comment suggestions.

7
  • You could simply use db_update() instead of checking if there is a row for that data. db_update() updates the existing row, or creates it when it doesn't exist.
    – apaderno
    Jun 22, 2015 at 9:58
  • Also, you don't use variable_set() in this case, but $conf in settings.php since it is something that should be changed before Drupal completes its bootstrap phase.
    – apaderno
    Jun 22, 2015 at 10:00
  • @kiam Think you mean db_merge()?
    – Clive
    Jun 22, 2015 at 10:07
  • Wouldn't I need to get the key if I use db_merge, and doesn't that basically check if it exists, and then updates/inserts? I am not sure that makes it better? Regarding the variable, I'd assumed this would be done on module install. I'll make that clearer.
    – Paul
    Jun 22, 2015 at 10:12
  • @Clive Ops... Yes, that.
    – apaderno
    Jun 22, 2015 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.