+ Start a Discussion
ashish jadhav 9ashish jadhav 9 

When to use batch class and when to use future method? What is the difference?

Hey guys, I have a small doubt, when should we go for batch or future method? need a small example to understand.
DeepthiDeepthi (Salesforce Developers) 
Hi Ashish,

Future Annotation:  Future Annotation is used to separate methods that are to be executed asynchronously.
If Future Annotation is not used in a web service callout, the thread will wait until the response comes and other processes will not be executed.

Batch Apex: Batch Apex is used to separate tasks that are going to handle more records(complex long running jobs) in background process. Batch Apex also runs asynchronously.
If Batch Apex is not used for handling bulk records, we will hit governor limits set by Salesforce.com.

Also, refer the below links for more details:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm 

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_invoking_future_methods.htm

https://developer.salesforce.com/page/Best_Practice:_Use_future_Appropriately 

http://www.slideshare.net/bachovski/batchable-vs-future-vs-queueable

Hope this helps you!
Best Regards,
Deepthi
nagendra 6989nagendra 6989
Hi ashish jadhav9,

Batch Apex :

Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex.
Need of Batch Apex: - As you all might know about the salesforce governor limits on its data. When you want to fetch thousands of records or fire DML on thousands of rows on objects it is very complex in salesforce and it does not allow you to operate on more than certain number of records which satisfies the Governor limits.
But for medium to large enterprises, it is essential to manage thousands of records every day. Adding/editing/deleting them when needed.
Salesforce has come up with a powerful concept called Batch Apex. Batch Apex allows you to handle more number of records and manipulate them by using a specific syntax.
We have to create an global apex class which extends Database.Batchable Interface because of which the salesforce compiler will know, this class incorporates batch jobs. Below is a sample class which is designed to delete all the records of Account object (Lets say your organization contains more than 50 thousand records and you want to mass delete all of them).
 
Examples:-
global class deleteAccounts implements Database.Batchable
{
global final String Query;
global deleteAccounts(String q)
{
Query=q;
}
 
global Database.QueryLocator start(Database.BatchableContext BC)
{
return Database.getQueryLocator(query);
}
 
global void execute(Database.BatchableContext BC,List scope)
{
List <Account> lstAccount = new list<Account>();
for(Sobject s : scope)
{
 Account a = (Account)s;
lstAccount.add(a);
}
Delete lstAccount;
}
 
global void finish(Database.BatchableContext BC)
{
                //Send an email to the User after your batch completes
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {‘sforce2009@gmail.com’};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Batch Job is done‘);
mail.setPlainTextBody('The batch Apex job processed ');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
 
//This is how the batch class is called.
id batchinstanceid = database.executeBatch(new deleteAccounts(‘select Id from Account’))


Future Method :

A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you’d like to run in its own thread, on its own time. You can also make use of future methods to isolate DML operations on different sObject types to prevent the mixed DML error. Each future method is queued and executes when system resources become available. That way, the execution of your code doesn’t have to wait for the completion of a long-running operation. A benefit of using future methods is that some governor limits are higher, such as SOQL query limits and heap size limits.
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
    }
}
Methods with the future annotation must be static methods, and can only return a void type. The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types. Methods with the futureannotation cannot take sObjects or objects as arguments.
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.

Difference between Future annotation and Batch apex :

User-added image

Kindly mark it as solved if it helps you.

Best Regards,
Nagendra.P
9848950830