+ Start a Discussion
Lakshmi SLakshmi S 

Batch apex, Queueable apex and @Future method

HI All,

Q). What is a Batch Apex,Queueable Apex and @Future methods?, What are the differences between them and when we are going to use these classes?
Can anyone explain these classes.......
 
Best Answer chosen by Lakshmi S
SandhyaSandhya (Salesforce Developers) 
Hi Lakshmi Narasimha,


Queueable Interface methods and Future methods are Asynchronous Apex Processes that add jobs to the job queue and each job runs when system resources become available, so it doesn’t delay the execution of the main Apex logic. They also share a benefit of having some higher governor limits than synchronous Apex, such as heap size limits (12 MB),  number of SOQL queries issued (200) and Maximum CPU time on the Salesforce servers (60k ms). But the Queueable interface methods are a step up from the future methods because they also come with these additional benefits (according to Salesforce release notes):

To define a future method, simply annotate it with the future annotation, as follows:-
 
global class FutureClass
{
    @future
    public static void myFutureMethod()
    {   
         // Perform some operations
    }
}


NOTE :-

1) Methods with the future annotation must be static methods
2) can only return a void type
3) The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types
4) Methods with the future annotation cannot take sObjects or objects as arguments.
5) You can invoke future methods the same way you invoke any other method. However, a future method can’t invoke another future method
6) No more than 50 method calls per Apex invocation
7) Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do not count against your limits for the number of queued jobs
8) The maximum number of future method invocations per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater
9) To test methods defined with the future annotation, call the class containing the method in a startTest(), stopTest() code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously


IMP:-
The reason why sObjects can’t be passed as arguments to future methods is because the sObject might change between the time you call the method and the time it executes. In this case, the future method will get the old sObject values and might overwrite them.  To work with sObjects that already exist in the database, pass the sObject ID instead (or collection of IDs) and use the ID to perform a query for the most up-to-date record. The following example shows how to do so with a list of IDs


Example of a future method that makes a callout to an external service. Notice that the annotation takes an extra parameter (callout=true) to indicate that callouts are allowed
 
global class FutureMethodExample
{
    @future(callout=true)
    public static void getStockQuotes(String acctName)
    {   
         // Perform a callout to an external service
    }

}


Queueable Interface

Getting an ID for your job: When you submit your job by invoking the System.enqueueJob method, the method returns the ID of the new job. This ID corresponds to the ID of the AsyncApexJob record. You can use this ID to identify your job and monitor its progress, either through the Salesforce user interface in the Apex Jobs page, or programmatically by querying your record from AsyncApexJob.
Chaining jobs: You can chain one job to another by starting a second job from a running job. Chaining jobs is useful if you need to do some processing that depends on another process to have run first.


Below is an example of how to implement the Queueable interface.
 
public class AsyncExecutionExample implements Queueable {
     public void execute(QueueableContext context) {
          Account a = new Account(Name='Acme',Phone='(415) 555-1212');
          insert a; 
     }
}
You can add the class to a job queue by calling this method.
ID jobID = System.enqueueJob(new AsyncExecutionExample());


If you have a second class that also implements the Queueable interface and you want it to run after the class above is done, you can chain them together like this:
 
public class AsyncExecutionExample implements Queueable {
     public void execute(QueueableContext context) {
          Account a = new Account(Name='Acme',Phone='(415) 555-1212');
          insert a; 

         // Chain this job to next job by submitting the next job
         System.enqueueJob(new SecondJob());
     }
}


Thanks and Regards
sandhya

 

All Answers

SandhyaSandhya (Salesforce Developers) 
Hi Lakshmi Narasimha,

1.The Batchable Interface

 • When should you use it? -
Complex long running processes (thousands of records)
- Asynchronous processing - Scheduled jobs
• How can you define a Batch? - Implement Database.Batchable -
Define start(), execute() and finish() methods

The Batchable Interface
• Advantages -
It can process up to 50m records
It can be scheduled to run at a particular time
• Disadvantages - Only five concurrent batch jobs running at a time* - It’s difficult to troubleshoot - Execution may be delayed based on server availability -
@future methods are not allowed - Can’t use getContent/getContentAsPDF methods - and a few more governor limits…

2. @future method •
When should I use it?
 - When it’s not a batch (group = 2 or more) - Asynchronous processing (simple and often)
- Long-running operations (callouts to external web services) - Separating mixed DML operations
• How can I define @future method?
 - @future annotation - Must be static and return void - Specify (callout=true) to allow callouts
@future method
• Advantages - Asynchronous processing without a concurrent limit (queue)
- Easier and quicker to implement as opposed to Batch
- Can use getContent/getContentAsPDF methods
• Disadvantages - Parameters passed in can be only of Primitive type
 - - Can’t chain @future methods - Difficult access to job ID

3. The Queueable Interface
 • When should I use it?
 - When Batch and @future need to meet in the middle - Chaining jobs
 - You need @future method with support for non-primitive types
 - Asynchronous monitoring
 • How can I define Queueable Apex?
- Implement the Queueable interface - Define execute() method
• How can I enqueue a job? - ID jobID = System.enqueueJob(new MyQueueableClass());
The Queueable Interface • Advantages
 - Asynchronous processing with non-primitive arguments
- Easy access to the job ID - Chaining jobs* •
 Disadvantages - Can’t have more than one job in the chain that does callouts

Which one to use? Batchable @future Queueable
 - Good at processing large number of records (50m) and tasks are not time-crucial
 - Can be scheduled to run at a certain time 
- Maximum of 5 concurrent jobs running at a time 
- You need good error handling for troubleshooting 
- Quick async processing (typically one record at a time) e.g. avoid mixed DML or a web service callout - Faster than a Batch - Easy to implement
 - Only accepts primitive type arguments - Can’t chain jobs 
- Hard to monitor
 - Quick async processing that supports primitive types 
- Faster than a batch
 - Ability to chain jobs - Can’t have more than one job doing callouts within the chain - Can be monitored


Please accept my solution as Best Answer if my reply was helpful. It will make it available for other as the proper solution. If you felt I went above and beyond, you can give me kudos.
 
Thanks and Regards
Sandhya


 
Lakshmi SLakshmi S
Hi Sandhya,

Could you please explain with examples?
Lakshmi SLakshmi S
*Hi **Sandhya,* If Possible, could u please explain with example programs(Queueable Apex & @Future methods) How can we call @Future methods? execution procedure? Is it possible for scheduling queueable apex classes & @Future methods, then how? If you have a time u can explain these queries, otherwise ignore this mail.. *Regards,* *Narasimha.*
SandhyaSandhya (Salesforce Developers) 
Hi Lakshmi Narasimha,


Queueable Interface methods and Future methods are Asynchronous Apex Processes that add jobs to the job queue and each job runs when system resources become available, so it doesn’t delay the execution of the main Apex logic. They also share a benefit of having some higher governor limits than synchronous Apex, such as heap size limits (12 MB),  number of SOQL queries issued (200) and Maximum CPU time on the Salesforce servers (60k ms). But the Queueable interface methods are a step up from the future methods because they also come with these additional benefits (according to Salesforce release notes):

To define a future method, simply annotate it with the future annotation, as follows:-
 
global class FutureClass
{
    @future
    public static void myFutureMethod()
    {   
         // Perform some operations
    }
}


NOTE :-

1) Methods with the future annotation must be static methods
2) can only return a void type
3) The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types
4) Methods with the future annotation cannot take sObjects or objects as arguments.
5) You can invoke future methods the same way you invoke any other method. However, a future method can’t invoke another future method
6) No more than 50 method calls per Apex invocation
7) Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do not count against your limits for the number of queued jobs
8) The maximum number of future method invocations per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater
9) To test methods defined with the future annotation, call the class containing the method in a startTest(), stopTest() code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously


IMP:-
The reason why sObjects can’t be passed as arguments to future methods is because the sObject might change between the time you call the method and the time it executes. In this case, the future method will get the old sObject values and might overwrite them.  To work with sObjects that already exist in the database, pass the sObject ID instead (or collection of IDs) and use the ID to perform a query for the most up-to-date record. The following example shows how to do so with a list of IDs


Example of a future method that makes a callout to an external service. Notice that the annotation takes an extra parameter (callout=true) to indicate that callouts are allowed
 
global class FutureMethodExample
{
    @future(callout=true)
    public static void getStockQuotes(String acctName)
    {   
         // Perform a callout to an external service
    }

}


Queueable Interface

Getting an ID for your job: When you submit your job by invoking the System.enqueueJob method, the method returns the ID of the new job. This ID corresponds to the ID of the AsyncApexJob record. You can use this ID to identify your job and monitor its progress, either through the Salesforce user interface in the Apex Jobs page, or programmatically by querying your record from AsyncApexJob.
Chaining jobs: You can chain one job to another by starting a second job from a running job. Chaining jobs is useful if you need to do some processing that depends on another process to have run first.


Below is an example of how to implement the Queueable interface.
 
public class AsyncExecutionExample implements Queueable {
     public void execute(QueueableContext context) {
          Account a = new Account(Name='Acme',Phone='(415) 555-1212');
          insert a; 
     }
}
You can add the class to a job queue by calling this method.
ID jobID = System.enqueueJob(new AsyncExecutionExample());


If you have a second class that also implements the Queueable interface and you want it to run after the class above is done, you can chain them together like this:
 
public class AsyncExecutionExample implements Queueable {
     public void execute(QueueableContext context) {
          Account a = new Account(Name='Acme',Phone='(415) 555-1212');
          insert a; 

         // Chain this job to next job by submitting the next job
         System.enqueueJob(new SecondJob());
     }
}


Thanks and Regards
sandhya

 
This was selected as the best answer
Lakshmi SLakshmi S
Hi Sandhya,

How to call Future class or @Future methods ?
Could you please give me an example...
Shravani M 9Shravani M 9
Hi,
I am uploading 200 records by using dataloader . I am using trigger and queable for calling future method . Its working fine for 50 records, but when i am uploading 200 records i am getting error "Too many queuable calls 51"
Musunuru SurekhaMusunuru Surekha

Hi,

There is a governor limit for @future methods. We can have only 50 callouts per transaction. This limit can be hit easily if we use @future methods in triggers. So, it is not recommended to use @future in triggers.

goravsethgoravseth
It appears that @Sandhya copied verbatim from this SlideShare deck by Boris Bachovski.  Cmon man.  Life is too short for this nonsense.

https://www.slideshare.net/mobile/bachovski/batchable-vs-future-vs-queueable
farukh shaikhfarukh shaikh
Do visit here for complete understanding,

http://www.sfdc-lightning.com/