Future Annotation:
Batch Apex:
Example: Delete all the account having Rating 'Cold'
global class deleteAccounts implements Database.Batchable{
global Database.QueryLocator start(Database.BatchableContext BC){
string query = 'select id,name,Rating,Owner from Account';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC,List scope){
List <Account> lstAccount = new list<Account>();
for(Sobject s : scope){
Account a = new Account();
if(s.Rating=='Cold'){
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[] {'dummyemail@gmail.com'};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Batch Job is completed');
mail.setPlainTextBody('The batch Apex job processed ');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
- Future Annotation(@Future) 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.
- Mixed DML Exception can be avoided with the use of @future annotation.
- @future annotation - Must be static and return void - Specify (callout=true) to allow callouts.
- Parameters passed to this can only be primitive.
- Tracking future is difficult as you don't have any jobId to track it.
- Future can be used to resolve mixed DML exception.
Example: You cannot insert a setup object and a non-setup object in same context. You'll encounter mixed DML exception. @Future comes for rescue in this situation.
public class MixedDMLFuture {
public static void useFutureMethod() {
//First DML operation- Insertion of non-setup object(Account)
Account a = new Account(Name='Vydehi Hospital');
insert a;
// This next operation (insert a user with a role) can't be mixed with the previous insert unless it is within a future method.
/*// Other DML Operation -- commented the code with a reason, if you use the commented code you will get mixed DML exception error
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
// Create new user with a non-null user role ID
User u = new User(alias = 'ranvk', email='dummyMail@gmail',
emailencodingkey='UTF-8', lastname='niru',languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
timezonesidkey='America/Los_Angeles',
username='dM@gmail.com');
insert u; */
//Call future method to insert a user(setup object) with a role.
UtilClass.insertUserWithRole( 'dummyMail@gmail.com', 'ranvk', 'dM@gmail.com', 'niru');
}
}
public class UtilClass {
@future
public static void insertUserWithRole(String uname, String al, String em, String lname) {
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
// Create new user with a non-null user role ID
User u = new User(alias = al, email=em, emailencodingkey='UTF-8',
lastname=lname, languagelocalekey='en_US', localesidkey='en_US',
profileid = p.Id, userroleid = r.Id, timezonesidkey='America/Los_Angeles',
username=uname);
insert u;
}
}
Batch Apex:
- Batch Apex is used to separate tasks that are going to handle more records(complex long running jobs) in background process.
- To avoid hitting governor limits we use Batch Apex for handling bulk records.
- It can process up to 50 million records. It can also be scheduled to run at a particular time.
- Only 5 concurrent batch can execute simultaneously. It is difficult to track the progress of the execution.
- We cannot use @future annotation. As asynchronous call is not allowed from batch apex.
Example: Delete all the account having Rating 'Cold'
global class deleteAccounts implements Database.Batchable{
global Database.QueryLocator start(Database.BatchableContext BC){
string query = 'select id,name,Rating,Owner from Account';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC,List scope){
List <Account> lstAccount = new list<Account>();
for(Sobject s : scope){
Account a = new Account();
if(s.Rating=='Cold'){
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[] {'dummyemail@gmail.com'};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Batch Job is completed');
mail.setPlainTextBody('The batch Apex job processed ');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
No comments:
Post a Comment