SlideShare une entreprise Scribd logo
1  sur  34
Drupal 7 Queues
Drupal Queues New to Drupal 7 First in first out data structure Used internally by Drupal Uses OO principles Fully customisable
Why Use Queues? Batch processing of large amounts of data/items Delay processing of complex calculations so system load is more stable Sequential processing of items Preventing API service black listing
Drupal 7 Implementations Batch API Cron Aggregator Module Update Module
Drupal Queues Found in the file: /modules/system/system.queue.inc Classes are used to wrap queue functionality Reliable vs Non-reliable
Reliable Generally kept in database table Every item will be executed at least once Items exist over several requests If the request fails then queue remains intact
Non-reliable Generally kept in memory only All items might exist in a single request No guarantee that all queue items will be executed No guarantee that all items will be executed in order If request fails then queue might be lost
Drupal Queue Classes
DrupalQueue Single static method get() DrupalQueue::get('my_queue'); Returns a queue object of a given name and a given type (reliable or non-reliable) Force reliable queue by passing TRUE as second parameter Default returned class is SystemQueue  Essentially a queue object factory
SystemQueue Example of a reliable queue class Implements  DrupalReliableQueueInterface Uses the database table  queue  to store and retrieve the queue Items are 'leased' to ensure no two processes get the same queue item Default class for new queues
queue Table Created at Drupal install
MemoryQueue Example of an non-reliable queue class All queue items are stored in memory $queue  parameter in class contains the queue Also implements item leasing
System Variables Three system variables are used by DrupalQueue to decide what sort of object to return 'queue_class_' . $name Default is NULL queue_default_class Default is SystemQueue queue_default_reliable_class Default is SystemQueue
Using Drupal Queues
Create A Queue $queue = DrupalQueue::get('my_queue', TRUE); $item = array( 'dataitem1' => 'something', 'int' => 123 ); $queue->createItem($item); echo $queue->numberOfItems(); // 1
Create A MemoryQueue variable_set('queue_default_class', 'MemoryQueue'); $queue = DrupalQueue::get('my_queue'); $item = array( 'dataitem1' => 'something', 'int' => 123 ); $queue->createItem($item); echo $queue->numberOfItems(); // 1
Get Item From Queue $queue = DrupalQueue::get('my_queue'); $got_item = $queue->claimItem(); echo $got_item->data['dataitem1'];
Retrieved Item Structure stdClass Object ( [data] => Array ( [dataitem1] => something [qwe] => 123 ) [item_id] => 89 )
Change Lease Length Can pass the lease time (in seconds) to claimItem() $got_item = $queue->claimItem( 100 );
Release Or Delete releaseItem() resets the lease time $queue->releaseItem($got_item); deleteItem() removes item from queue $queue->deleteItem($got_item);
Customizing Create custom queue class Create variable called “queue_class_” . $name Value is the class name of your queue class Call  DrupalQueue::get()  with the variable $name as a string
Customizing Reliable class MUST implement  DrupalReliableQueueInterface Can also extend SystemQueue All Queue classes should at least implement  DrupalQueueInterface
Using Custom Classes variable_set('queue_class_mycustom', 'MyCustomQueueClass'); $queue = DrupalQueue::get('mycustom');
Stack Class Last in first out implementation class Stack extends SystemQueue { public function claimItem($lease_time = 30) { while (TRUE) { $item = db_query_range('SELECT data, item_id FROM {queue} q WHERE  expire = 0 AND name = :name ORDER BY created  DESC ', 0, 1, array(':name' => $this->name))->fetchObject(); // ...
EventQueue Class Required as part of the NWDUG website Any items added would not be available for 45 minutes to give a period of grace after creating an event node class EventQueue extends SystemQueue { public function claimItem($lease_time = 30) { while (TRUE) { $item = db_query_range('SELECT data, item_id FROM {queue} q WHERE expire = 0 AND name = :name  AND created >= UNIX_TIMESTAMP(DATE_ADD(NOW(), INTERVAL 2700 SECOND))  ORDER BY created ASC', 0, 1, array(':name' => $this->name))->fetchObject();
WatchdogSystemQueue Extends SystemQueue and creates a log every time anything is done Maintains SystemQueue functionality
WatchdogSystemQueue class WatchdogSystemQueue extends SystemQueue { public function __construct($name) { watchdog('queue', '%name queue created',  array('%name' => $name)); parent::__construct($name); } public function createItem($data) { watchdog('queue', 'Item created : %data',  array('%data' => print_r($data, TRUE))); parent::createItem($data); } public function claimItem($lease_time = 3600) { $return_value = parent::claimItem($lease_time); watchdog('queue', 'Item claimed %item (lease time = %lease)',  array( '%item' => print_r($return_value, TRUE), '%lease' => $lease_time));  return $return_value; } //....
RandomMemoryQueue Extends the MemoryQueue class Items are added in order but are retrieved in random order
RandomMemoryQueue class RandomMemoryQueue extends MemoryQueue { public function claimItem($lease_time = 30) {  $available_items = array(); // Extract the remining available items foreach ($this->queue as $key => $item) { if ($item->expire == 0) { $available_items[] = $item; } } // Randomly select one (if available) if (count($available_items) > 0) { $queue_length = count($this->queue);  $rand_item = rand(0, $queue_length - 1); $item = $available_items[$rand_item]; $item->expire = time() + $lease_time; return $item; } return FALSE; } }
Creating And Destroying DrupalQueueInterface has two methods available for creating and destroying the queue createQueue() Should be called within an install hook deleteQueue() Should be called within an uninstall hook
Tips Unless you really need to rewrite the entire class it is best to extend SystemQueue or MemoryQueue For open source projects try to keep the same retrieved item structure as the system queues No checks for unique items in default system queues
Resources Drupal Queues API http://api.drupal.org/api/drupal/modules--system--system.queue.inc/group/queue/7 http://bit.ly/kuphnc Queue UI Module http://drupal.org/project/queue_ui Source code is well documented /modules/system/system.queue.inc Full write up of this talk on #! code http://www.hashbangcode.com/
Questions? $queue = DrupalQueue::get('questions'); $question = $queue->claimItem(); echo $question->data['question'];
Blog http:///www.norton42.org.uk/ Twitter @philipnorton42 #! code http://www.hashbangcode.com/ #! code on Twitter @hashbangcode Philip Norton

Contenu connexe

Tendances

Introduction to Amazon CloudFront - Pop-up Loft Tel Aviv
Introduction to Amazon CloudFront - Pop-up Loft Tel AvivIntroduction to Amazon CloudFront - Pop-up Loft Tel Aviv
Introduction to Amazon CloudFront - Pop-up Loft Tel AvivAmazon Web Services
 
[225]빅데이터를 위한 분산 딥러닝 플랫폼 만들기
[225]빅데이터를 위한 분산 딥러닝 플랫폼 만들기[225]빅데이터를 위한 분산 딥러닝 플랫폼 만들기
[225]빅데이터를 위한 분산 딥러닝 플랫폼 만들기NAVER D2
 
Network Security and Access Control in AWS
Network Security and Access Control in AWSNetwork Security and Access Control in AWS
Network Security and Access Control in AWSAmazon Web Services
 
Deep Dive on Amazon Neptune (DAT403) - AWS re:Invent 2018
Deep Dive on Amazon Neptune (DAT403) - AWS re:Invent 2018Deep Dive on Amazon Neptune (DAT403) - AWS re:Invent 2018
Deep Dive on Amazon Neptune (DAT403) - AWS re:Invent 2018Amazon Web Services
 
AWS Summit Seoul 2023 | AWS의 개발자를 위한 신규 서비스 소개 Amazon CodeCatalyst & Amazon C...
AWS Summit Seoul 2023 | AWS의 개발자를 위한 신규 서비스 소개 Amazon CodeCatalyst & Amazon C...AWS Summit Seoul 2023 | AWS의 개발자를 위한 신규 서비스 소개 Amazon CodeCatalyst & Amazon C...
AWS Summit Seoul 2023 | AWS의 개발자를 위한 신규 서비스 소개 Amazon CodeCatalyst & Amazon C...Amazon Web Services Korea
 
내 서비스에는 어떤 데이터베이스가 맞는걸까? - 이혁 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021
내 서비스에는 어떤 데이터베이스가 맞는걸까? - 이혁 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021내 서비스에는 어떤 데이터베이스가 맞는걸까? - 이혁 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021
내 서비스에는 어떤 데이터베이스가 맞는걸까? - 이혁 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021Amazon Web Services Korea
 
Windows Azure Virtual Machines
Windows Azure Virtual MachinesWindows Azure Virtual Machines
Windows Azure Virtual MachinesClint Edmonson
 
AWS Route53 Fundamentals
AWS Route53 FundamentalsAWS Route53 Fundamentals
AWS Route53 FundamentalsPiyush Agrawal
 
Introduction to GCP presentation
Introduction to GCP presentationIntroduction to GCP presentation
Introduction to GCP presentationMohit Kachhwani
 
Using Amazon VPC Flow Logs for Predictive Security Analytics (NET319) - AWS r...
Using Amazon VPC Flow Logs for Predictive Security Analytics (NET319) - AWS r...Using Amazon VPC Flow Logs for Predictive Security Analytics (NET319) - AWS r...
Using Amazon VPC Flow Logs for Predictive Security Analytics (NET319) - AWS r...Amazon Web Services
 
AWS 환경에서의 위협 탐지 및 사냥 - 신은수, AWS 솔루션즈 아키텍트:: AWS Summit Online Korea 2020
AWS 환경에서의 위협 탐지 및 사냥 - 신은수, AWS  솔루션즈 아키텍트::  AWS Summit Online Korea 2020AWS 환경에서의 위협 탐지 및 사냥 - 신은수, AWS  솔루션즈 아키텍트::  AWS Summit Online Korea 2020
AWS 환경에서의 위협 탐지 및 사냥 - 신은수, AWS 솔루션즈 아키텍트:: AWS Summit Online Korea 2020Amazon Web Services Korea
 
Search Your DynamoDB Data with Amazon Elasticsearch Service (ANT302) - AWS re...
Search Your DynamoDB Data with Amazon Elasticsearch Service (ANT302) - AWS re...Search Your DynamoDB Data with Amazon Elasticsearch Service (ANT302) - AWS re...
Search Your DynamoDB Data with Amazon Elasticsearch Service (ANT302) - AWS re...Amazon Web Services
 
Encryption and Key Management in AWS
Encryption and Key Management in AWS Encryption and Key Management in AWS
Encryption and Key Management in AWS Amazon Web Services
 
Advanced Load Balancer/Traffic Manager and App Gateway for Microsoft Azure
Advanced Load Balancer/Traffic Manager and App Gateway for Microsoft AzureAdvanced Load Balancer/Traffic Manager and App Gateway for Microsoft Azure
Advanced Load Balancer/Traffic Manager and App Gateway for Microsoft AzureKemp
 
Oracle Cloud Infrastructure (OCI)
Oracle Cloud Infrastructure (OCI)Oracle Cloud Infrastructure (OCI)
Oracle Cloud Infrastructure (OCI)emmajones88
 
Provisioning Datadog with Terraform
Provisioning Datadog with TerraformProvisioning Datadog with Terraform
Provisioning Datadog with TerraformMatt Spurlin
 
Services comparison among Microsoft Azure AWS and Google Cloud Platform
Services comparison among Microsoft Azure AWS and Google Cloud PlatformServices comparison among Microsoft Azure AWS and Google Cloud Platform
Services comparison among Microsoft Azure AWS and Google Cloud Platformindu Yadav
 

Tendances (20)

Introduction to Amazon CloudFront - Pop-up Loft Tel Aviv
Introduction to Amazon CloudFront - Pop-up Loft Tel AvivIntroduction to Amazon CloudFront - Pop-up Loft Tel Aviv
Introduction to Amazon CloudFront - Pop-up Loft Tel Aviv
 
[225]빅데이터를 위한 분산 딥러닝 플랫폼 만들기
[225]빅데이터를 위한 분산 딥러닝 플랫폼 만들기[225]빅데이터를 위한 분산 딥러닝 플랫폼 만들기
[225]빅데이터를 위한 분산 딥러닝 플랫폼 만들기
 
Google cloud
Google cloudGoogle cloud
Google cloud
 
Network Security and Access Control in AWS
Network Security and Access Control in AWSNetwork Security and Access Control in AWS
Network Security and Access Control in AWS
 
Deep Dive on Amazon Neptune (DAT403) - AWS re:Invent 2018
Deep Dive on Amazon Neptune (DAT403) - AWS re:Invent 2018Deep Dive on Amazon Neptune (DAT403) - AWS re:Invent 2018
Deep Dive on Amazon Neptune (DAT403) - AWS re:Invent 2018
 
AWS Summit Seoul 2023 | AWS의 개발자를 위한 신규 서비스 소개 Amazon CodeCatalyst & Amazon C...
AWS Summit Seoul 2023 | AWS의 개발자를 위한 신규 서비스 소개 Amazon CodeCatalyst & Amazon C...AWS Summit Seoul 2023 | AWS의 개발자를 위한 신규 서비스 소개 Amazon CodeCatalyst & Amazon C...
AWS Summit Seoul 2023 | AWS의 개발자를 위한 신규 서비스 소개 Amazon CodeCatalyst & Amazon C...
 
내 서비스에는 어떤 데이터베이스가 맞는걸까? - 이혁 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021
내 서비스에는 어떤 데이터베이스가 맞는걸까? - 이혁 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021내 서비스에는 어떤 데이터베이스가 맞는걸까? - 이혁 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021
내 서비스에는 어떤 데이터베이스가 맞는걸까? - 이혁 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021
 
AWS Direct Connect
AWS Direct ConnectAWS Direct Connect
AWS Direct Connect
 
Windows Azure Virtual Machines
Windows Azure Virtual MachinesWindows Azure Virtual Machines
Windows Azure Virtual Machines
 
AWS Route53 Fundamentals
AWS Route53 FundamentalsAWS Route53 Fundamentals
AWS Route53 Fundamentals
 
Introduction to GCP presentation
Introduction to GCP presentationIntroduction to GCP presentation
Introduction to GCP presentation
 
Using Amazon VPC Flow Logs for Predictive Security Analytics (NET319) - AWS r...
Using Amazon VPC Flow Logs for Predictive Security Analytics (NET319) - AWS r...Using Amazon VPC Flow Logs for Predictive Security Analytics (NET319) - AWS r...
Using Amazon VPC Flow Logs for Predictive Security Analytics (NET319) - AWS r...
 
AWS 환경에서의 위협 탐지 및 사냥 - 신은수, AWS 솔루션즈 아키텍트:: AWS Summit Online Korea 2020
AWS 환경에서의 위협 탐지 및 사냥 - 신은수, AWS  솔루션즈 아키텍트::  AWS Summit Online Korea 2020AWS 환경에서의 위협 탐지 및 사냥 - 신은수, AWS  솔루션즈 아키텍트::  AWS Summit Online Korea 2020
AWS 환경에서의 위협 탐지 및 사냥 - 신은수, AWS 솔루션즈 아키텍트:: AWS Summit Online Korea 2020
 
Search Your DynamoDB Data with Amazon Elasticsearch Service (ANT302) - AWS re...
Search Your DynamoDB Data with Amazon Elasticsearch Service (ANT302) - AWS re...Search Your DynamoDB Data with Amazon Elasticsearch Service (ANT302) - AWS re...
Search Your DynamoDB Data with Amazon Elasticsearch Service (ANT302) - AWS re...
 
Encryption and Key Management in AWS
Encryption and Key Management in AWS Encryption and Key Management in AWS
Encryption and Key Management in AWS
 
Advanced Load Balancer/Traffic Manager and App Gateway for Microsoft Azure
Advanced Load Balancer/Traffic Manager and App Gateway for Microsoft AzureAdvanced Load Balancer/Traffic Manager and App Gateway for Microsoft Azure
Advanced Load Balancer/Traffic Manager and App Gateway for Microsoft Azure
 
Oracle Cloud Infrastructure (OCI)
Oracle Cloud Infrastructure (OCI)Oracle Cloud Infrastructure (OCI)
Oracle Cloud Infrastructure (OCI)
 
Provisioning Datadog with Terraform
Provisioning Datadog with TerraformProvisioning Datadog with Terraform
Provisioning Datadog with Terraform
 
Services comparison among Microsoft Azure AWS and Google Cloud Platform
Services comparison among Microsoft Azure AWS and Google Cloud PlatformServices comparison among Microsoft Azure AWS and Google Cloud Platform
Services comparison among Microsoft Azure AWS and Google Cloud Platform
 
Aws Autoscaling
Aws AutoscalingAws Autoscaling
Aws Autoscaling
 

Similaire à Drupal 7 Queues

Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011camp_drupal_ua
 
Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Evgeny Nikitin
 
MUC - Moodle Universal Cache
MUC - Moodle Universal CacheMUC - Moodle Universal Cache
MUC - Moodle Universal CacheTim Hunt
 
Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4JoeDinaso
 
Introduction to cron queue
Introduction to cron queueIntroduction to cron queue
Introduction to cron queueADCI Solutions
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectJonathan Wage
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 
The state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinThe state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinNida Ismail Shah
 
DRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEWDRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEWDrupalCamp Kyiv
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit TestingMike Lively
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowkatbailey
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowWork at Play
 
Advanced moduledevelopment d6_slideshare
Advanced moduledevelopment d6_slideshareAdvanced moduledevelopment d6_slideshare
Advanced moduledevelopment d6_slideshareOpevel
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection apiMatthieu Aubry
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011Maurizio Pelizzone
 
Php on the desktop and php gtk2
Php on the desktop and php gtk2Php on the desktop and php gtk2
Php on the desktop and php gtk2Elizabeth Smith
 

Similaire à Drupal 7 Queues (20)

Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
 
Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014
 
MUC - Moodle Universal Cache
MUC - Moodle Universal CacheMUC - Moodle Universal Cache
MUC - Moodle Universal Cache
 
Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4
 
Intro to The PHP SPL
Intro to The PHP SPLIntro to The PHP SPL
Intro to The PHP SPL
 
Introduction to cron queue
Introduction to cron queueIntroduction to cron queue
Introduction to cron queue
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
The state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinThe state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon Dublin
 
DRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEWDRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEW
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit Testing
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Advanced moduledevelopment d6_slideshare
Advanced moduledevelopment d6_slideshareAdvanced moduledevelopment d6_slideshare
Advanced moduledevelopment d6_slideshare
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011
 
Php on the desktop and php gtk2
Php on the desktop and php gtk2Php on the desktop and php gtk2
Php on the desktop and php gtk2
 

Plus de Philip Norton

Getting Into Drupal 8 Configuration
Getting Into Drupal 8 ConfigurationGetting Into Drupal 8 Configuration
Getting Into Drupal 8 ConfigurationPhilip Norton
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionPhilip Norton
 
Webform and Drupal 8
Webform and Drupal 8Webform and Drupal 8
Webform and Drupal 8Philip Norton
 
Acquia Drupal Certification
Acquia Drupal CertificationAcquia Drupal Certification
Acquia Drupal CertificationPhilip Norton
 
Becoming A Drupal Master Builder
Becoming A Drupal Master BuilderBecoming A Drupal Master Builder
Becoming A Drupal Master BuilderPhilip Norton
 
Drupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthDrupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthPhilip Norton
 
Drupal 8 Configuration Management
Drupal 8 Configuration ManagementDrupal 8 Configuration Management
Drupal 8 Configuration ManagementPhilip Norton
 
Getting Started With Jenkins And Drupal
Getting Started With Jenkins And DrupalGetting Started With Jenkins And Drupal
Getting Started With Jenkins And DrupalPhilip Norton
 
Making The Drupal Pill Easier To Swallow
Making The Drupal Pill Easier To SwallowMaking The Drupal Pill Easier To Swallow
Making The Drupal Pill Easier To SwallowPhilip Norton
 

Plus de Philip Norton (13)

ReactPHP
ReactPHPReactPHP
ReactPHP
 
Getting Into Drupal 8 Configuration
Getting Into Drupal 8 ConfigurationGetting Into Drupal 8 Configuration
Getting Into Drupal 8 Configuration
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
 
Drupal 8 Services
Drupal 8 ServicesDrupal 8 Services
Drupal 8 Services
 
Webform and Drupal 8
Webform and Drupal 8Webform and Drupal 8
Webform and Drupal 8
 
Acquia Drupal Certification
Acquia Drupal CertificationAcquia Drupal Certification
Acquia Drupal Certification
 
Becoming A Drupal Master Builder
Becoming A Drupal Master BuilderBecoming A Drupal Master Builder
Becoming A Drupal Master Builder
 
Drupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthDrupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp North
 
Drupal 8 Configuration Management
Drupal 8 Configuration ManagementDrupal 8 Configuration Management
Drupal 8 Configuration Management
 
Getting Started With Jenkins And Drupal
Getting Started With Jenkins And DrupalGetting Started With Jenkins And Drupal
Getting Started With Jenkins And Drupal
 
Drupal theming
Drupal themingDrupal theming
Drupal theming
 
Drush
DrushDrush
Drush
 
Making The Drupal Pill Easier To Swallow
Making The Drupal Pill Easier To SwallowMaking The Drupal Pill Easier To Swallow
Making The Drupal Pill Easier To Swallow
 

Dernier

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 

Dernier (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Drupal 7 Queues

  • 2. Drupal Queues New to Drupal 7 First in first out data structure Used internally by Drupal Uses OO principles Fully customisable
  • 3. Why Use Queues? Batch processing of large amounts of data/items Delay processing of complex calculations so system load is more stable Sequential processing of items Preventing API service black listing
  • 4. Drupal 7 Implementations Batch API Cron Aggregator Module Update Module
  • 5. Drupal Queues Found in the file: /modules/system/system.queue.inc Classes are used to wrap queue functionality Reliable vs Non-reliable
  • 6. Reliable Generally kept in database table Every item will be executed at least once Items exist over several requests If the request fails then queue remains intact
  • 7. Non-reliable Generally kept in memory only All items might exist in a single request No guarantee that all queue items will be executed No guarantee that all items will be executed in order If request fails then queue might be lost
  • 9. DrupalQueue Single static method get() DrupalQueue::get('my_queue'); Returns a queue object of a given name and a given type (reliable or non-reliable) Force reliable queue by passing TRUE as second parameter Default returned class is SystemQueue Essentially a queue object factory
  • 10. SystemQueue Example of a reliable queue class Implements DrupalReliableQueueInterface Uses the database table queue to store and retrieve the queue Items are 'leased' to ensure no two processes get the same queue item Default class for new queues
  • 11. queue Table Created at Drupal install
  • 12. MemoryQueue Example of an non-reliable queue class All queue items are stored in memory $queue parameter in class contains the queue Also implements item leasing
  • 13. System Variables Three system variables are used by DrupalQueue to decide what sort of object to return 'queue_class_' . $name Default is NULL queue_default_class Default is SystemQueue queue_default_reliable_class Default is SystemQueue
  • 15. Create A Queue $queue = DrupalQueue::get('my_queue', TRUE); $item = array( 'dataitem1' => 'something', 'int' => 123 ); $queue->createItem($item); echo $queue->numberOfItems(); // 1
  • 16. Create A MemoryQueue variable_set('queue_default_class', 'MemoryQueue'); $queue = DrupalQueue::get('my_queue'); $item = array( 'dataitem1' => 'something', 'int' => 123 ); $queue->createItem($item); echo $queue->numberOfItems(); // 1
  • 17. Get Item From Queue $queue = DrupalQueue::get('my_queue'); $got_item = $queue->claimItem(); echo $got_item->data['dataitem1'];
  • 18. Retrieved Item Structure stdClass Object ( [data] => Array ( [dataitem1] => something [qwe] => 123 ) [item_id] => 89 )
  • 19. Change Lease Length Can pass the lease time (in seconds) to claimItem() $got_item = $queue->claimItem( 100 );
  • 20. Release Or Delete releaseItem() resets the lease time $queue->releaseItem($got_item); deleteItem() removes item from queue $queue->deleteItem($got_item);
  • 21. Customizing Create custom queue class Create variable called “queue_class_” . $name Value is the class name of your queue class Call DrupalQueue::get() with the variable $name as a string
  • 22. Customizing Reliable class MUST implement DrupalReliableQueueInterface Can also extend SystemQueue All Queue classes should at least implement DrupalQueueInterface
  • 23. Using Custom Classes variable_set('queue_class_mycustom', 'MyCustomQueueClass'); $queue = DrupalQueue::get('mycustom');
  • 24. Stack Class Last in first out implementation class Stack extends SystemQueue { public function claimItem($lease_time = 30) { while (TRUE) { $item = db_query_range('SELECT data, item_id FROM {queue} q WHERE expire = 0 AND name = :name ORDER BY created DESC ', 0, 1, array(':name' => $this->name))->fetchObject(); // ...
  • 25. EventQueue Class Required as part of the NWDUG website Any items added would not be available for 45 minutes to give a period of grace after creating an event node class EventQueue extends SystemQueue { public function claimItem($lease_time = 30) { while (TRUE) { $item = db_query_range('SELECT data, item_id FROM {queue} q WHERE expire = 0 AND name = :name AND created >= UNIX_TIMESTAMP(DATE_ADD(NOW(), INTERVAL 2700 SECOND)) ORDER BY created ASC', 0, 1, array(':name' => $this->name))->fetchObject();
  • 26. WatchdogSystemQueue Extends SystemQueue and creates a log every time anything is done Maintains SystemQueue functionality
  • 27. WatchdogSystemQueue class WatchdogSystemQueue extends SystemQueue { public function __construct($name) { watchdog('queue', '%name queue created', array('%name' => $name)); parent::__construct($name); } public function createItem($data) { watchdog('queue', 'Item created : %data', array('%data' => print_r($data, TRUE))); parent::createItem($data); } public function claimItem($lease_time = 3600) { $return_value = parent::claimItem($lease_time); watchdog('queue', 'Item claimed %item (lease time = %lease)', array( '%item' => print_r($return_value, TRUE), '%lease' => $lease_time)); return $return_value; } //....
  • 28. RandomMemoryQueue Extends the MemoryQueue class Items are added in order but are retrieved in random order
  • 29. RandomMemoryQueue class RandomMemoryQueue extends MemoryQueue { public function claimItem($lease_time = 30) { $available_items = array(); // Extract the remining available items foreach ($this->queue as $key => $item) { if ($item->expire == 0) { $available_items[] = $item; } } // Randomly select one (if available) if (count($available_items) > 0) { $queue_length = count($this->queue); $rand_item = rand(0, $queue_length - 1); $item = $available_items[$rand_item]; $item->expire = time() + $lease_time; return $item; } return FALSE; } }
  • 30. Creating And Destroying DrupalQueueInterface has two methods available for creating and destroying the queue createQueue() Should be called within an install hook deleteQueue() Should be called within an uninstall hook
  • 31. Tips Unless you really need to rewrite the entire class it is best to extend SystemQueue or MemoryQueue For open source projects try to keep the same retrieved item structure as the system queues No checks for unique items in default system queues
  • 32. Resources Drupal Queues API http://api.drupal.org/api/drupal/modules--system--system.queue.inc/group/queue/7 http://bit.ly/kuphnc Queue UI Module http://drupal.org/project/queue_ui Source code is well documented /modules/system/system.queue.inc Full write up of this talk on #! code http://www.hashbangcode.com/
  • 33. Questions? $queue = DrupalQueue::get('questions'); $question = $queue->claimItem(); echo $question->data['question'];
  • 34. Blog http:///www.norton42.org.uk/ Twitter @philipnorton42 #! code http://www.hashbangcode.com/ #! code on Twitter @hashbangcode Philip Norton