SlideShare a Scribd company logo
1 of 19
Force.com Batch Apex 
Sujit Kumar 
Zenolocity LLC © 2012 - 2024
Overview 
• Concepts 
• Batchable Interface 
• Guidelines 
• Example Apex Batch Job 
• Execution and Monitoring 
• Stateful Batch Apex 
• Iterable Batch 
• Limitations 
• Testing and Scheduling
Concepts 
• Large, data-intensive processing. 
• Scope: set of records Batch Apex works on. One to 50 
million records. Scope is usually expressed as a SOQL 
statement, which is contained in a Query Locator, a system 
object that is exempt from the normal governor limits on 
SOQL. 
• Batch Job: Asynchronous, run in background. UI to list, 
monitor and cancel batch jobs. 
• Transactions: Units of work running the same code within a 
batch job, subject to governor limits. Up to 200 records. 
The scope is split into several transactions, each committed 
to the database independently. Stateless. Parallel or serial. 
• 5 Active Batch Jobs per Org.
Batchable Interface 
• start() - return a QueryLocator or an Iterable that 
describes the scope of the batch job. 
• execute() – splits the records from the previous step 
into several transactions, each of which operates on up 
to 200 records. 
• The records are provided in the scope argument of the 
execute method. 
• Each invocation of execute is a separate transaction. 
• If an uncaught exception is in a transaction, no further 
transactions are processed and the entire batch job is 
stopped.
Transactions in Batch Job 
• Transactions that complete successfully are never 
rolled back. 
• If an error in a transaction stops the batch, the 
transactions executed up to that point remain in 
the database. 
• Cannot use savepoints to achieve a single 
pseudo-transaction across the entire batch job. 
• If you must achieve job-wide rollback, this can be 
implemented in the form of a compensating 
batch job that reverses the actions of the failed 
job.
Batchable (contd…) 
• finish() - Invoked once at the end of a batch 
job. 
• The job ends when all transactions in the 
scope have been processed successfully, or if 
processing has failed. 
• Regardless of success or failure, finish is 
always called. 
• No code required in the finish method.
Batch Apex Class 
• Must implement the Database.Batchable 
interface. Parameterized interface, so needs a 
type name. Use SObject for batches with a 
QueryLocator scope, or any database object 
type for an Iterable scope. 
• The class must be global, hence methods must 
be global as well.
Batchable Context 
• The BatchableContext object argument in all 
three methods contains a method called getJobId 
to get unique ID of the current batch job. 
• jobID can be used to look up additional 
information about the batch job in the standard 
database object AsyncApexJob. 
• You can also pass this identifier to the 
System.abortJob method to stop processing of 
the batch job.
Guidelines 
• Single DB Object – source data from a single 
DB object, no web services, 
• Simple scope of work – single SOQL typically. 
• Minimal shared state – each unit of work is 
independent. 
• Limited transactionality – rollback requires 
custom code. 
• Not time critical – no guarantee on when it is 
executed and how long it will run.
Running Batch Jobs 
• 4 ways: execute from a VF page, schedule it or kick off 
from a trigger or run it from the Execute Anonymous 
view in the Force.com IDE. 
• Execute from the Anonymous view. 
HelloBatchApex batch = new HelloBatchApex(); 
Id jobId = Database.executeBatch(batch); 
System.debug('Started Batch Apex job: ' + jobId); 
Pass an extra argument to executeBatch to control the scope.
Job States 
• Queued 
• Processing 
• Aborted 
• Successful
4 Different Logs in Debug Logs 
• Results of evaluating the code in the Execute 
Anonymous view. 
• Invocation of the start method to prepare the 
dataset for the batch. 
• Results of running the execute method, where 
the batch job performs its work on the subsets of 
the data. 
• All the transactions have been processed, so the 
finish method is called to allow post-processing 
to occur.
Stateful Batch 
• Batch Apex is stateless by default. That means for 
each run of the execute method, you receive a 
fresh copy of your object. All fields of the class , 
both static and instance are initialized. 
• If your batch process needs information that is 
shared across transactions, one approach is to 
make the Batch Apex class itself stateful by 
implementing the Stateful interface. 
• This instructs Force.com to preserve the values of 
your static and instance variables between 
transactions.
Compare QueryLocator and Iterable 
Batch 
Feature QueryLocator Iterable Batch 
Number of Records 1 to 50 million Max of 50k records 
How it works? Uses exactly 1 SOQL 
without governor limits 
Custom Apex Code, can 
use complex criteria, 
subject to governor limits.
Iterable Batch 
• Global class that must implement 2 interfaces: 
the Iterator interface and the Iterable interface. 
• Iterator – hasNext() and next() global methods. 
• Iterable – single global method called Iterator(). 
• You could write two separate classes, one to 
implement each interface. Or you can implement 
both interfaces in the same class.
Limitations of Apex Batch 
• No future methods allowed. 
• Run as system user, so have permission to read and 
write all data in the org. 
• Max heap size is 6MB. 
• Exactly 1 callout to external systems allowed for each 
invocation of start, execute and finish. Must implement 
Database.AllowsCallouts interface. 
• Reduce the default 200 records per transaction if 
intensive work needs to be done that may exceed the 
governor limits. 
• Max number of queued or active jobs in an org is 5.
Testing Batch Apex 
• Batch Apex can be tested like any Apex code, although 
you are limited to a single transaction’s worth of data 
(one invocation of the execute method). 
• A batch job started within a test runs synchronously, 
and does not count against the organization’s limit of 5 
batch jobs. 
public static testmethod void testBatch() { 
Test.startTest(); 
HelloBatchApex batch = new HelloBatchApex(); 
ID jobId = Database.executeBatch(batch); 
Test.stopTest(); 
}
Schedule Batch Apex 
• Enables any Apex code, not just Batch Apex, to be 
scheduled to run asynchronously at regular time intervals. 
• An Apex class that can be scheduled by Force.com must 
implement the Schedulable interface. Marker Interface => 
no methods. 
• Code that is executed by the scheduler runs as the system 
user, so sharing rules or other access controls are not 
enforced. 
• At most 10 classes can be scheduled at one time. 
• Programmatic approach: 
System.schedule('Scheduled Test', '0 0 1 * * ?', 
new HelloSchedulable());
Create Scheduled Batch Job 
global class HelloSchedulable 
implements Schedulable { 
global void execute(SchedulableContext sc) 
{ 
HelloBatchApex batch = new 
HelloBatchApex(); 
Database.executeBatch(batch); 
} 
}

More Related Content

What's hot

Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overview
honglee71
 
Introduction to apex code
Introduction to apex codeIntroduction to apex code
Introduction to apex code
EdwinOstos
 

What's hot (20)

Salesforce Development Best Practices
Salesforce Development Best PracticesSalesforce Development Best Practices
Salesforce Development Best Practices
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
Governor limits
Governor limitsGovernor limits
Governor limits
 
Fast parallel data loading with the bulk API
Fast parallel data loading with the bulk APIFast parallel data loading with the bulk API
Fast parallel data loading with the bulk API
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overview
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queries
 
Maximizing Salesforce Lightning Experience and Lightning Component Performance
Maximizing Salesforce Lightning Experience and Lightning Component PerformanceMaximizing Salesforce Lightning Experience and Lightning Component Performance
Maximizing Salesforce Lightning Experience and Lightning Component Performance
 
Introduction to apex code
Introduction to apex codeIntroduction to apex code
Introduction to apex code
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Relational database- Fundamentals
Relational database- FundamentalsRelational database- Fundamentals
Relational database- Fundamentals
 
Apex code (Salesforce)
Apex code (Salesforce)Apex code (Salesforce)
Apex code (Salesforce)
 
Apex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsApex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong Foundations
 
Salesforce Basic Development
Salesforce Basic DevelopmentSalesforce Basic Development
Salesforce Basic Development
 
Defensive Apex Programming
Defensive Apex ProgrammingDefensive Apex Programming
Defensive Apex Programming
 
All About Test Class in #Salesforce
All About Test Class in #SalesforceAll About Test Class in #Salesforce
All About Test Class in #Salesforce
 
Introduction to ETL process
Introduction to ETL process Introduction to ETL process
Introduction to ETL process
 
Apex collection patterns
Apex collection patternsApex collection patterns
Apex collection patterns
 
salesforce triggers interview questions and answers
salesforce triggers interview questions and answerssalesforce triggers interview questions and answers
salesforce triggers interview questions and answers
 
Best Practices with Apex in 2022.pdf
Best Practices with Apex in 2022.pdfBest Practices with Apex in 2022.pdf
Best Practices with Apex in 2022.pdf
 

Similar to SFDC Batch Apex

Similar to SFDC Batch Apex (20)

Distributed Model Validation with Epsilon
Distributed Model Validation with EpsilonDistributed Model Validation with Epsilon
Distributed Model Validation with Epsilon
 
Spring batch
Spring batchSpring batch
Spring batch
 
Hyperbatch (LoteRapido) - Punta Dreamin' 2017
Hyperbatch (LoteRapido) - Punta Dreamin' 2017Hyperbatch (LoteRapido) - Punta Dreamin' 2017
Hyperbatch (LoteRapido) - Punta Dreamin' 2017
 
SFDC Introduction to Apex
SFDC Introduction to ApexSFDC Introduction to Apex
SFDC Introduction to Apex
 
Taking Full Advantage of Galera Multi Master Cluster
Taking Full Advantage of Galera Multi Master ClusterTaking Full Advantage of Galera Multi Master Cluster
Taking Full Advantage of Galera Multi Master Cluster
 
Enhanced Reframework Session_16-07-2022.pptx
Enhanced Reframework Session_16-07-2022.pptxEnhanced Reframework Session_16-07-2022.pptx
Enhanced Reframework Session_16-07-2022.pptx
 
python_development.pptx
python_development.pptxpython_development.pptx
python_development.pptx
 
Salesforce Apex Hours :- Hyper batch
Salesforce Apex Hours :- Hyper batchSalesforce Apex Hours :- Hyper batch
Salesforce Apex Hours :- Hyper batch
 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable Apex
 
Using The Right Tool For The Job
Using The Right Tool For The JobUsing The Right Tool For The Job
Using The Right Tool For The Job
 
Alternate for scheduled apex using flow builder
Alternate for scheduled apex using flow builderAlternate for scheduled apex using flow builder
Alternate for scheduled apex using flow builder
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
File Processing - Batch Process Execution
File Processing - Batch Process ExecutionFile Processing - Batch Process Execution
File Processing - Batch Process Execution
 
File Processing - Process Execution Solution
File Processing - Process Execution SolutionFile Processing - Process Execution Solution
File Processing - Process Execution Solution
 
Introducing the Apache Flink Kubernetes Operator
Introducing the Apache Flink Kubernetes OperatorIntroducing the Apache Flink Kubernetes Operator
Introducing the Apache Flink Kubernetes Operator
 
Building large scale, job processing systems with Scala Akka Actor framework
Building large scale, job processing systems with Scala Akka Actor frameworkBuilding large scale, job processing systems with Scala Akka Actor framework
Building large scale, job processing systems with Scala Akka Actor framework
 
Performance tuning Grails applications
Performance tuning Grails applicationsPerformance tuning Grails applications
Performance tuning Grails applications
 
Salesforce Meetup 18 April 2015 - Apex Trigger & Scheduler Framworks
Salesforce Meetup 18 April 2015 - Apex Trigger & Scheduler FramworksSalesforce Meetup 18 April 2015 - Apex Trigger & Scheduler Framworks
Salesforce Meetup 18 April 2015 - Apex Trigger & Scheduler Framworks
 
Operating System lab
Operating System labOperating System lab
Operating System lab
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 

More from Sujit Kumar

Java equals hashCode Contract
Java equals hashCode ContractJava equals hashCode Contract
Java equals hashCode Contract
Sujit Kumar
 
Java Comparable and Comparator
Java Comparable and ComparatorJava Comparable and Comparator
Java Comparable and Comparator
Sujit Kumar
 
Java build tools
Java build toolsJava build tools
Java build tools
Sujit Kumar
 
Java Web services
Java Web servicesJava Web services
Java Web services
Sujit Kumar
 

More from Sujit Kumar (20)

Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with java
 
SFDC Database Basics
SFDC Database BasicsSFDC Database Basics
SFDC Database Basics
 
SFDC Database Security
SFDC Database SecuritySFDC Database Security
SFDC Database Security
 
SFDC Social Applications
SFDC Social ApplicationsSFDC Social Applications
SFDC Social Applications
 
SFDC Other Platform Features
SFDC Other Platform FeaturesSFDC Other Platform Features
SFDC Other Platform Features
 
SFDC Outbound Integrations
SFDC Outbound IntegrationsSFDC Outbound Integrations
SFDC Outbound Integrations
 
SFDC Inbound Integrations
SFDC Inbound IntegrationsSFDC Inbound Integrations
SFDC Inbound Integrations
 
SFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSFDC UI - Advanced Visualforce
SFDC UI - Advanced Visualforce
 
SFDC UI - Introduction to Visualforce
SFDC UI -  Introduction to VisualforceSFDC UI -  Introduction to Visualforce
SFDC UI - Introduction to Visualforce
 
SFDC Deployments
SFDC DeploymentsSFDC Deployments
SFDC Deployments
 
SFDC Data Loader
SFDC Data LoaderSFDC Data Loader
SFDC Data Loader
 
SFDC Advanced Apex
SFDC Advanced Apex SFDC Advanced Apex
SFDC Advanced Apex
 
SFDC Database Additional Features
SFDC Database Additional FeaturesSFDC Database Additional Features
SFDC Database Additional Features
 
Introduction to SalesForce
Introduction to SalesForceIntroduction to SalesForce
Introduction to SalesForce
 
More about java strings - Immutability and String Pool
More about java strings - Immutability and String PoolMore about java strings - Immutability and String Pool
More about java strings - Immutability and String Pool
 
Hibernate First and Second level caches
Hibernate First and Second level cachesHibernate First and Second level caches
Hibernate First and Second level caches
 
Java equals hashCode Contract
Java equals hashCode ContractJava equals hashCode Contract
Java equals hashCode Contract
 
Java Comparable and Comparator
Java Comparable and ComparatorJava Comparable and Comparator
Java Comparable and Comparator
 
Java build tools
Java build toolsJava build tools
Java build tools
 
Java Web services
Java Web servicesJava Web services
Java Web services
 

Recently uploaded

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
Safe Software
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

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
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
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
 

SFDC Batch Apex

  • 1. Force.com Batch Apex Sujit Kumar Zenolocity LLC © 2012 - 2024
  • 2. Overview • Concepts • Batchable Interface • Guidelines • Example Apex Batch Job • Execution and Monitoring • Stateful Batch Apex • Iterable Batch • Limitations • Testing and Scheduling
  • 3. Concepts • Large, data-intensive processing. • Scope: set of records Batch Apex works on. One to 50 million records. Scope is usually expressed as a SOQL statement, which is contained in a Query Locator, a system object that is exempt from the normal governor limits on SOQL. • Batch Job: Asynchronous, run in background. UI to list, monitor and cancel batch jobs. • Transactions: Units of work running the same code within a batch job, subject to governor limits. Up to 200 records. The scope is split into several transactions, each committed to the database independently. Stateless. Parallel or serial. • 5 Active Batch Jobs per Org.
  • 4. Batchable Interface • start() - return a QueryLocator or an Iterable that describes the scope of the batch job. • execute() – splits the records from the previous step into several transactions, each of which operates on up to 200 records. • The records are provided in the scope argument of the execute method. • Each invocation of execute is a separate transaction. • If an uncaught exception is in a transaction, no further transactions are processed and the entire batch job is stopped.
  • 5. Transactions in Batch Job • Transactions that complete successfully are never rolled back. • If an error in a transaction stops the batch, the transactions executed up to that point remain in the database. • Cannot use savepoints to achieve a single pseudo-transaction across the entire batch job. • If you must achieve job-wide rollback, this can be implemented in the form of a compensating batch job that reverses the actions of the failed job.
  • 6. Batchable (contd…) • finish() - Invoked once at the end of a batch job. • The job ends when all transactions in the scope have been processed successfully, or if processing has failed. • Regardless of success or failure, finish is always called. • No code required in the finish method.
  • 7. Batch Apex Class • Must implement the Database.Batchable interface. Parameterized interface, so needs a type name. Use SObject for batches with a QueryLocator scope, or any database object type for an Iterable scope. • The class must be global, hence methods must be global as well.
  • 8. Batchable Context • The BatchableContext object argument in all three methods contains a method called getJobId to get unique ID of the current batch job. • jobID can be used to look up additional information about the batch job in the standard database object AsyncApexJob. • You can also pass this identifier to the System.abortJob method to stop processing of the batch job.
  • 9. Guidelines • Single DB Object – source data from a single DB object, no web services, • Simple scope of work – single SOQL typically. • Minimal shared state – each unit of work is independent. • Limited transactionality – rollback requires custom code. • Not time critical – no guarantee on when it is executed and how long it will run.
  • 10. Running Batch Jobs • 4 ways: execute from a VF page, schedule it or kick off from a trigger or run it from the Execute Anonymous view in the Force.com IDE. • Execute from the Anonymous view. HelloBatchApex batch = new HelloBatchApex(); Id jobId = Database.executeBatch(batch); System.debug('Started Batch Apex job: ' + jobId); Pass an extra argument to executeBatch to control the scope.
  • 11. Job States • Queued • Processing • Aborted • Successful
  • 12. 4 Different Logs in Debug Logs • Results of evaluating the code in the Execute Anonymous view. • Invocation of the start method to prepare the dataset for the batch. • Results of running the execute method, where the batch job performs its work on the subsets of the data. • All the transactions have been processed, so the finish method is called to allow post-processing to occur.
  • 13. Stateful Batch • Batch Apex is stateless by default. That means for each run of the execute method, you receive a fresh copy of your object. All fields of the class , both static and instance are initialized. • If your batch process needs information that is shared across transactions, one approach is to make the Batch Apex class itself stateful by implementing the Stateful interface. • This instructs Force.com to preserve the values of your static and instance variables between transactions.
  • 14. Compare QueryLocator and Iterable Batch Feature QueryLocator Iterable Batch Number of Records 1 to 50 million Max of 50k records How it works? Uses exactly 1 SOQL without governor limits Custom Apex Code, can use complex criteria, subject to governor limits.
  • 15. Iterable Batch • Global class that must implement 2 interfaces: the Iterator interface and the Iterable interface. • Iterator – hasNext() and next() global methods. • Iterable – single global method called Iterator(). • You could write two separate classes, one to implement each interface. Or you can implement both interfaces in the same class.
  • 16. Limitations of Apex Batch • No future methods allowed. • Run as system user, so have permission to read and write all data in the org. • Max heap size is 6MB. • Exactly 1 callout to external systems allowed for each invocation of start, execute and finish. Must implement Database.AllowsCallouts interface. • Reduce the default 200 records per transaction if intensive work needs to be done that may exceed the governor limits. • Max number of queued or active jobs in an org is 5.
  • 17. Testing Batch Apex • Batch Apex can be tested like any Apex code, although you are limited to a single transaction’s worth of data (one invocation of the execute method). • A batch job started within a test runs synchronously, and does not count against the organization’s limit of 5 batch jobs. public static testmethod void testBatch() { Test.startTest(); HelloBatchApex batch = new HelloBatchApex(); ID jobId = Database.executeBatch(batch); Test.stopTest(); }
  • 18. Schedule Batch Apex • Enables any Apex code, not just Batch Apex, to be scheduled to run asynchronously at regular time intervals. • An Apex class that can be scheduled by Force.com must implement the Schedulable interface. Marker Interface => no methods. • Code that is executed by the scheduler runs as the system user, so sharing rules or other access controls are not enforced. • At most 10 classes can be scheduled at one time. • Programmatic approach: System.schedule('Scheduled Test', '0 0 1 * * ?', new HelloSchedulable());
  • 19. Create Scheduled Batch Job global class HelloSchedulable implements Schedulable { global void execute(SchedulableContext sc) { HelloBatchApex batch = new HelloBatchApex(); Database.executeBatch(batch); } }