Asynchronous Apex
In a nutshell, asynchronous
Apex is used to run processes in a separate thread, at a later time.
An
asynchronous process is a process or function that executes a task "in the
background" without the user having to wait for the task to finish
Asynchronous Apex for callouts to external systems, operations that
require higher limits, and code that needs to run at a certain time. The key
benefits of asynchronous processing include:
User
efficiency
asynchronous processing the user can get on with their work, the
processing can be done in the background and the user can see the results at
their convenience
By
allowing some features of the platform to execute when resources become available
at some point in the future, resources can be managed and scaled quickly. This
allows the platform to handle more jobs using parallel processing.
Higher
Limits
Future Apex
Future
Apex is used to run processes in a separate thread, at a later time when system
resources become available.
Future methods 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. Notably, future methods can’t take standard or custom objects as
arguments. A common pattern is to pass the method a List of record IDs that you
want to process asynchronously
global class SomeClass {
@future
public
static void someFutureMethod(List<Id> recordIds) {
List<Account>
accounts = [Select Id, Name from Account Where Id IN :recordIds];
//
process account records to do awesome stuff
}
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------public
class AccountProcessor {
@future
public
static void countContacts(set<id> setId){
list<account> lstAccount=[select id,Number_of_Contacts__c ,(select
id from contacts) from account where id IN :setId];
for(account acc: lstAccount){
list<contact> lstcontact= acc.contacts;
acc.Number_of_Contacts__c =lstcontact.size();
}
update lstAccount;
}
}
@IsTest
public class AccountProcessorTest {
public static testmethod void
TestAccountProcessorTest()
{
Account a = new Account();
a.Name = 'My Account';
Insert a;
Contact cont = New Contact();
cont.FirstName ='ajay';
cont.LastName ='singh';
cont.AccountId = a.Id;
Insert cont;
set<Id> setAccId = new Set<ID>();
setAccId.add(a.id);
Test.startTest();
AccountProcessor.countContacts(setAccId);
Test.stopTest();
Account
ACC = [select Number_of_Contacts__c from Account where id = :a.id LIMIT 1];
System.assertEquals ( Integer.valueOf(ACC.Number_of_Contacts__c) ,1);
}
}
No comments:
Post a Comment