SlideShare ist ein Scribd-Unternehmen logo
1 von 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); 
} 
}

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Sql loader good example
Sql loader good exampleSql loader good example
Sql loader good example
 
Load Data Fast!
Load Data Fast!Load Data Fast!
Load Data Fast!
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
 
SQL Server Stored procedures
SQL Server Stored proceduresSQL Server Stored procedures
SQL Server Stored procedures
 
Exception handling
Exception handlingException handling
Exception handling
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 
Triggers and order of execution1
Triggers and order of execution1Triggers and order of execution1
Triggers and order of execution1
 
Php
PhpPhp
Php
 
Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Access modifiers in Python
Access modifiers in PythonAccess modifiers in Python
Access modifiers in Python
 
Java Collections
Java  Collections Java  Collections
Java Collections
 

Ähnlich wie SFDC Batch Apex

Distributed Model Validation with Epsilon
Distributed Model Validation with EpsilonDistributed Model Validation with Epsilon
Distributed Model Validation with EpsilonSina Madani
 
Batch Apex in Salesforce
Batch Apex in SalesforceBatch Apex in Salesforce
Batch Apex in SalesforceDavid Helgerson
 
Hyperbatch (LoteRapido) - Punta Dreamin' 2017
Hyperbatch (LoteRapido) - Punta Dreamin' 2017Hyperbatch (LoteRapido) - Punta Dreamin' 2017
Hyperbatch (LoteRapido) - Punta Dreamin' 2017Daniel Peter
 
SFDC Introduction to Apex
SFDC Introduction to ApexSFDC Introduction to Apex
SFDC Introduction to ApexSujit Kumar
 
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.pptxRohit Radhakrishnan
 
python_development.pptx
python_development.pptxpython_development.pptx
python_development.pptxLemonReddy1
 
Salesforce Apex Hours :- Hyper batch
Salesforce Apex Hours :- Hyper batchSalesforce Apex Hours :- Hyper batch
Salesforce Apex Hours :- Hyper batchAmit Chaudhary
 
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 JobChris Baldock
 
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 builderKadharBashaJ
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
File Processing - Batch Process Execution
File Processing - Batch Process ExecutionFile Processing - Batch Process Execution
File Processing - Batch Process ExecutionAbimael Desales López
 
File Processing - Process Execution Solution
File Processing - Process Execution SolutionFile Processing - Process Execution Solution
File Processing - Process Execution SolutionAbimael Desales López
 
Introducing the Apache Flink Kubernetes Operator
Introducing the Apache Flink Kubernetes OperatorIntroducing the Apache Flink Kubernetes Operator
Introducing the Apache Flink Kubernetes OperatorFlink Forward
 
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 frameworkVignesh Sukumar
 
Performance tuning Grails applications
Performance tuning Grails applicationsPerformance tuning Grails applications
Performance tuning Grails applicationsLari Hotari
 
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 FramworksSumitkumar Shingavi
 

Ähnlich wie SFDC Batch Apex (20)

Asynchronous apex
Asynchronous apexAsynchronous apex
Asynchronous apex
 
Salesforce asynchronous apex
Salesforce asynchronous apexSalesforce asynchronous apex
Salesforce asynchronous apex
 
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
 
Batch Apex in Salesforce
Batch Apex in SalesforceBatch Apex in Salesforce
Batch Apex in Salesforce
 
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
 
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
 

Mehr von Sujit Kumar

Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with javaSujit Kumar
 
SFDC Database Basics
SFDC Database BasicsSFDC Database Basics
SFDC Database BasicsSujit Kumar
 
SFDC Database Security
SFDC Database SecuritySFDC Database Security
SFDC Database SecuritySujit Kumar
 
SFDC Social Applications
SFDC Social ApplicationsSFDC Social Applications
SFDC Social ApplicationsSujit Kumar
 
SFDC Other Platform Features
SFDC Other Platform FeaturesSFDC Other Platform Features
SFDC Other Platform FeaturesSujit Kumar
 
SFDC Outbound Integrations
SFDC Outbound IntegrationsSFDC Outbound Integrations
SFDC Outbound IntegrationsSujit Kumar
 
SFDC Inbound Integrations
SFDC Inbound IntegrationsSFDC Inbound Integrations
SFDC Inbound IntegrationsSujit Kumar
 
SFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSujit Kumar
 
SFDC UI - Introduction to Visualforce
SFDC UI -  Introduction to VisualforceSFDC UI -  Introduction to Visualforce
SFDC UI - Introduction to VisualforceSujit Kumar
 
SFDC Deployments
SFDC DeploymentsSFDC Deployments
SFDC DeploymentsSujit Kumar
 
SFDC Data Loader
SFDC Data LoaderSFDC Data Loader
SFDC Data LoaderSujit Kumar
 
SFDC Advanced Apex
SFDC Advanced Apex SFDC Advanced Apex
SFDC Advanced Apex Sujit Kumar
 
SFDC Database Additional Features
SFDC Database Additional FeaturesSFDC Database Additional Features
SFDC Database Additional FeaturesSujit Kumar
 
Introduction to SalesForce
Introduction to SalesForceIntroduction to SalesForce
Introduction to SalesForceSujit Kumar
 
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 PoolSujit Kumar
 
Hibernate First and Second level caches
Hibernate First and Second level cachesHibernate First and Second level caches
Hibernate First and Second level cachesSujit Kumar
 
Java equals hashCode Contract
Java equals hashCode ContractJava equals hashCode Contract
Java equals hashCode ContractSujit Kumar
 
Java Comparable and Comparator
Java Comparable and ComparatorJava Comparable and Comparator
Java Comparable and ComparatorSujit Kumar
 
Java build tools
Java build toolsJava build tools
Java build toolsSujit Kumar
 
Java Web services
Java Web servicesJava Web services
Java Web servicesSujit Kumar
 

Mehr von 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
 

Kürzlich hochgeladen

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.pdfOrbitshub
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
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
 
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 2024Victor Rentea
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
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
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
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
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

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
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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...
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
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
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

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); } }