Asynchronous Apex


 Synchronous : Synchronous means at a time in the flow it will execute, there is no delay. The code which is executing in the same thread is Synchronous apex.

Asynchronous Apex : An Asynchronous apex is the process or function that executes a task in the background without the user have to wait for the task to finish.  

Asynchronous apex is used to run process in a separate thread, at a late time. 

In Salesforce we have Asynchronous process like

  • Future Method
  • Queueable Apex
  • Batch Apex
  • Schedule Apex
What is Future Method?
Ans:  Future method runs in the background asynchronously.
  • To define future method we must use @Future annotation.
  • Future method should be static and returns only void. 
  • Parameters must be primitive data types, array of primitive data types, collection of primitive data types.
  • We can call future methd for executing long running process, such as callout to external web services.
  • We can use future method to prevent mixed DML operations
    • Mixed DML operation : When a user performs DML actions on Setup and non-Setup Objects in the same transaction, then mixed dml operation is generated.
    • Setup Objects : The Objects that interacts with Metadata like user, Profile, Layout etc
    • Non Setup Objects : All other objects such as Standard and Custom Objects are Non setup Objects.
  • In Future method we cannot track whether it is executed or not.
  • One Future method cannot call another future method.
  • If we are making a callout to an external service, we need to define callout=true by default callout is false.
  • Benifit of using Future method is that some governer limits are higher, such as SOQL queries and heap size.
  • Common Scenarios : Web Service Callout.
  • Overview : Run in their own thread, and do not start until resources are available.
Why Future method cannot take Sobjects as Parameters?
Ans: Sobject might change the time we call the method and the time it executes. In this case the future method will get the old object values and might overwrite them.

What is Queueable Apex?
Ans: Queueable apex is an asynchronous apex method. If we want to write Queueable class we must implement Queueable interface.
  • This Queueable interface has only one method "execute" and this method takes parameter as System.QueueableContext.
  • This interface enables us to add jobs to the queue and moniter them. We have to use System.enqueuejob method to add jobs to the queue.
  • When we submit the job to the queue using enqueuejob method, it returns an Id for that job.
  • This Id corresponds to the "AsyncApexJob" record Id. Using this Id we can moniter the job progress.
  • Queueable class can have non-primitive data types such as Sobjects or custom apex types as parameters.
  • Chaining Jobs : we can chain one job to another job, means that we can add one job to the current running job.
  • The main difference between Future and Queueable is We cannot chain jobs in Future, But we can in Queueable.
  • Common Scenarios : Performing sequential processing operations with external Web services.
  • Overview : Similar to future methods, but provide additional job chaining and allow more           complex data types to be used.
What is Batch Apex?
Ans: Batch Apex is used to run large jobs, such as thousands or millions of records that would exceed normal processing limits.
  • When we are writing Batch Apex, we must implement the interface Database.Batchable
  • This interface has three methods Start, Execute, Finish(as it is interface we need to implement all the three methods, Even if we miss one method it will throws error).
  • In Batch Apex the data process in the form of Batches, So we call it as Batch Apex.
  • Minimum Batch Size is 1 and Maximum is 2000, by default it will take 200(if we do not metion batch size).
  • We have to use Database.executeBatch method to execute the batch apex
  • Syntax for methods
    • Start : This method is used to collect the records or objects that are to be passed to Execute method. This method executes only once.
      • public  Database.queryLocator || Iterable<Sobject>    start(Database.BatchableContext    bc) 
    • Execute : This method is called for each batch of records passed to the method. Performs actual processing for each chunk or Batch of data passed to the mehod.
      • public void  execute(Database.BatchableContext   bc,   List<dataType>   Scope(size))
    • Finish : We can perform post commit logic like sending emails with he success or error information. It will execute only one time. 
      • public void  Finish(Database.BatchableContext  bc)
  • Common Scenarios : Data cleansing or archiving of records.
  • Overview  : Run large jobs that would exceed normal processing limits.

Batch Class in Apex

Batch class in salesforce is used to process a large number of records that would exceed the apex governor limits if processed normally. Batch class executes the code asynchronously.

Following are the advantages of batch class:


Every chunk of data in a batch class processed with a new set of governor limits which

ensure that code executes within the governor execution limits.


Database. Batchable interface must be implemented by an apex class to be used as a batch class. It provides three methods which must be implemented by the batch class.

Following are the three methods provided by Database. Batchable interface:

1. start():

This method generates the scope of records or objects to be processed by    the interface method execute. During the execution of batch, it is called once only. This method either returns a Database.QueryLocator object or  an iterable. The number of records retrieved by SQL query using the Database.QueryLocator object is 50 million records but using an iterable  the total number of records that can be retrieved by the SQL query is 50000 only. Iterable is used to generate complex scope for batch class.

Syntax of start method:

global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContextbc) {}

 

2. execute():

This method is used for the processing of each chunk of data. For each   c hunk of records execute method is called. The default batch size for execution is 200 records. Execute method takes two arguments:

A reference to the Database.BatchableContext object,

A list of sObjects, such as List<sObject>, or a list of parameterized types. Syntax of execute method:

global void execute(Database.BatchableContext BC, list<P>){}

 

3. flnish():

The finish method is called once during the execution of the batch class. Post-processing operations can be performed in the finish method. For example: sending the confirmation email. This method is called when all the batch get processed. Syntax of Finish method:

global void finish(Database.BatchableContext BC){}

 

Database.BatchableContext object:

Each method of the Database. Batchable interface has a reference to Database.BatchableContext object.

This object is used to track the progress of the batch job. Following are instance methods provided by BatchableContext :



getChildJobId(): This method returns the ID of a batch job that is currently processed. getJobId(): This method returns the ID of the batch job.

Below is the syntax of a batch class :

global class MyBatchClass implements Database.Batchable<sObject> {


global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContextbc) {

 

// collect the batches of records or objects to be passed to execute

}

global void execute(Database.BatchableContextbc, List<P> records){

// process each batch of records

}

global void finish(Database.BatchableContextbc){

// execute any post-processing operations

}

}

Database.executeBatch Method:

Database.executeBatch method is used for executing a batch class.

This method takes two parameters: Instance of the batch class to be

processed, Options parameter to specify the batch size if not specified it takes the default size of 200.

Syntax of Database.executeBatch :

Database.executeBatch(myBatchObject,scope)

Executing a batch class name MyBatchClass :

MyBatchClassmyBatchObject = new MyBatchClass();

Id batchId = Database.executeBatch(myBatchObject,100);


Database.stateful :

Batch class is stateless by default. Every time the execute method is called   a new copy of an object is received, all the variables of the class is initialized.

Database.stateful is implemented to make a batch class stateful.

If your batch class implemented the Database, stateful interface all the     instance variable retain their values, but the static variables get reset between the transaction.


Batch Apex is stateless by default. If a batch process needs information that is shared across transactions, then you need to implement a Stateful interface. If you specify Database.Stateful in the class definition, you can maintain state across these transactions.

For example, if your batch job is executing one logic and you need to send an email at end of the batch job with all successful records and failed records. For that, you can use Database.Stateful in the class definition.


What is difference between Database.QuerLocator and Iterable<Sobject>?
Ans:  If we use Database.QueryLocator the governer limits for total number of records retrieved by SOQL queries is bypassed(by default it will give 50000 records, we can get upto 50 million records).
  • If we want to fetch data using SOQL from database then use Database.QueryLocator

If we use Iterable<Sobject> the governer limit for the total number of records retrieved by SOQL query is still enforced.
  • If we need to use objects in the code instead of soql queries then we go for Iterable<Sobject>

What is BatchableContext?
Ans: It contains the Id of  running job.

Does the data transfer from one batch to another in Batch Apex?
Ans: By default the data will not exchange from one batch to another batch.
  • If we have requirement to transfer data from one batch to another batch, then we can use Database.stateful interface in Batch Apex.   
    • how to maintain state between the methods of batch class?
    • Ans: To maintain the state for the batch class, we should inherit Database.Stateful interface.    

To maintain variable value inside the Batch class, Database.Stateful is used.
Sample Class:
global class Class_Name implements Database.Batchable<sobject>, Database.Stateful{
    Integer i = 0;
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocatory('SELECT Id, Name, Sequence_Number__c FROM Employee__c');
    }
    
    global void execute(Database.BatchableContext bc, List<Employee__c> listEmployee){
        for(Employee__c e : listEmp){
            e.Sequence_Number__c = i;
            i += 1;
        }
    }
    
    global void finish(Database.BatchableContext bc){
    }
}
here i value will be maintained even though execute method is called several times.

can we use more than 1 interface in a single class?
Ans: Yes, We can use more than one interface in one class.

At a time how many batch jobs can run? 
Ans:  5

If there are more than 5 jobs where do they store?
Ans:  In flex queue they can store, after tfinishing any job in queue flex queue job will moved to queue.
  We can add 100 jobs in flex queue.

Can we call schedule apex in Batch apex?
Ans : We can call schedule apex  from finish method in Batch apex.

What happens if we call another batch in Execute method?
Ans: If  we call batch class from start or execute method then Salesforce throws the error System.AsyncException: Database.executeBatch cannot be called from a batch start, batch execute, or future method.

Can we write Constructor in Batch class?
Ans: Yes, We can write Constructor in Batch class.
 
What is Schedule apex?
Ans: Schedule apex delay's the execution so that we can run Apex classes at a specified time. Schedule apex is a class that runs at a regular interval of time.
  • To schedule an apex class, we need to implement  System.Schedulable interface
  • This interface has only one method  Execute and this method takes the parameter System.SchedulableContext
  • Use system.schedule method to execute the Schedule class, this method has three parameters
    • A name for job
    • CRON expression
    • The name of class 
  • We can query programmatically CronTrigger and CronJobDetail objects to count of Apex scheduled jobs.
  • Common Scenarios : Daily or weekly tasks.
  • Overview : Schedule Apex to run at a specified time.
How many ways we can Schedule an Schedule Apex?
Ans: We can do it in Two ways, Admin(Setup-->Quick Find-->Apex classes-->ScheduleApex) and Schedule Apex. 

Future
    Can Future method call another Future :  No
    Future can call Queueable Apex   :  No
    Future can call Batch Apex        :  No
    Future can call Schedule Apex  :  No

Queueable 
    Queueable can call Future         : Yes
    Queueable can call Queueable  :  Yes
    Queueable can call Batch Apex : Yes
    Queueable can call Schedule     : Yes

Batch Apex
    Batch Apex can call Future               : No
    Batch Apex can call Queueable        : No
    Batch Apex can call Batch Apex      : Yes (In Finish methhod we can call)
    Batch Apex can Schedule Apex        : Yes (In Finish method)

Schedule Apex
    Schedule Apex can call Future         : Yes
    Schedule Apex can call Queueable  : Yes
    Schedule Apex can call Batch Apex : Yes
    Schedule Apex can call Schedule     : Yes

Batch Apex:

·      What is Batch Apex in Salesforce?

Batch Apex is used to process large sets of    data asynchronously in smaller batches to avoid governor limits.


·      When would you use Batch Apex instead of    other Apex methods?

Batch Apex is used when you need to process large data sets (over 50,000 records) and need to bypass the synchronous execution time limits.

·      Explain the execution flow of Batch Apex.

The execute method is called for each batch of records, and the finish method is called after all batches are processed.

·      How do you specify the batch size in Batch Apex?


The batch size is automatically determined     by Salesforce, but you can specify the batch size using the optional "scope" parameter in the Database.executeBatch method.

·      How can you handle errors in Batch Apex?

You can implement the Database.RaisesException interface and handle exceptions using try-catch blocks in the execute method.

Queueable Apex:

·      What is Queueable Apex in Salesforce?

Queueable Apex is used to perform asynchronous processing of complex or long- running operations by adding them to the Apex job queue.


·      What are the advantages of Queueable Apex over Batch Apex?


Queueable Apex has a more flexible execution flow, doesn't have limitations on the number of records, and can be chained for complex processes.


·      Can you call a Queueable Apex class from a Batch Apex class?


Yes, you can call a Queueable Apex class from a Batch Apex class to perform additional   processing after the batch job completes.


Scheduled Apex:

·      What is Scheduled Apex in Salesforce?

Scheduled Apex allows you to schedule Apex classes to run at specified times or intervals.

·      How do you schedule an Apex class?

You can schedule an Apex class by using the System.schedule method or by using the Salesforce user interface.


·      Can you schedule multiple instances of the same Apex class?


Yes, you can schedule multiple instances of the same Apex class with different schedule times or intervals.

·      How do you handle exceptions in Scheduled Apex?

You can handle exceptions in Scheduled Apex by using try-catch blocks in the execute method.

Future Methods:

·      What is a Future Method in Salesforce?

A Future Method is used to run long- running operations asynchronously in a separate thread, allowing other code to continue executing.


·      What are the limitations of Future Methods?


Future Methods have limitations such as not being able to call them from triggers, limited callout limits, and not being able to perform DML operations on non-setup objects.


·      Can you call a Future Method from a Visualforce page?

Yes, you can call a Future Method from a Visualforce page, but you need to ensure that the method is annotated with @Future(callout=true) for callouts.


Scenario-based Questions:

·      Scenario: You need to update a large number of records with complex logic. Which   Apex feature would you use, and why?


Answer: I would use Batch Apex because it allows processing of large data sets and bypasses synchronous execution limits.


·      Scenario: You have a long-running operation that makes a callout to an external system. Which Apex feature would you use, and why?

Answer: I would use Queueable Apex because it supports long-running operations and asynchronous callouts.


·      Scenario: You need to perform a recurring  task every day at a specific time. Which Apex feature would you use, and why?

Answer: I would use Scheduled Apex to schedule the task to run at the specified time every day.

·      Scenario: You have a complex logic that requires multiple asynchronous operations to be executed in a specific order. Which Apex feature would you use, and why?

Answer: I would use Queueable Apex and chain the operations together to ensure the required order of execution.

·      Scenario: You need to make a callout to an external system from a trigger. Which Apex feature would you use, and why?


Answer: I would use a Future Method because it allows making callouts asynchronously from a trigger and doesn't have callout limits.


·      Scenario: How can you perform a callout to an external API asynchronously in Salesforce?


Answer: You can use a Future Method or Queueable Apex to perform asynchronous callouts to external APIs in Salesforce.


·      Scenario: What is the difference between Future Methods and Queueable Apex?


Answer: Future Methods are used for asynchronous processing, including callouts, and have certain limitations. Queueable Apex provides more flexibility, supports complex processing, and can be queued for execution.


·      Scenario: How can you chain multiple Queueable Apex jobs together?

Answer: You can chain multiple Queueable Apex jobs by implementing the `Queueable` interface and using the `System.enqueueJob` method to add jobs to the queue.

·      Scenario: How can you handle errors or exceptions in asynchronous Apex?

Answer: In asynchronous Apex, you can use try-catch blocks to handle exceptions and use the `addError` method to add custom error messages to records.


·      Scenario: Can you perform DML operations in a Future Method?


Answer: Yes, you can perform DML operations on non-setup objects in a Future Method. However, DML operations on setup  objects are not allowed.


·      Scenario: How do you make a callout from a Lightning Component or Visualforce page?

Answer: You can make a callout from a Lightning Component or Visualforce page by using Apex methods like Future Methods, Queueable Apex, or HttpCalloutMock interfaces for testing.


·      Scenario: How can you avoid hitting callout limits in Salesforce?


Answer: You can avoid hitting callout limits by using asynchronous Apex methods like Queueable Apex or Future Methods, which have separate limits from synchronous operations.


·      Scenario: How do you handle the order of execution for multiple asynchronous operations?

Answer: The order of execution can be controlled by chaining multiple Queueable Apex jobs or using dependent Future Methods to ensure sequential processing.

·      Scenario: How can you schedule an Apex class to run at specific intervals?  


Answer: You can use Scheduled Apex to schedule an Apex class to run at specific intervals, such as every hour, day, week, or month.


·      Scenario: How do you handle the governor limits in asynchronous Apex?


Answer: Asynchronous Apex has its own set of governor limits, and you need to consider these limits while designing and implementing your code to avoid hitting the limits.


Stops the specified job. The stopped job is still visible in the job queue in the Salesforce user interface.
Signature
public static Void abortJob(String jobId)

Parameters
jobId
Type: String
The jobId is the ID associated with either AsyncApexJob or CronTrigger.
Return Value
Type: Void

How can you track the progress of a Batch job?

Ans: The Database.executeBatch method returns the ID of the AsyncApexJob object.

ID batchprocessid = Database.executeBatch(reassign);AsyncApexJob aaj = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors
                    FROM AsyncApexJob WHERE ID =: batchprocessid ];

 

Database.insert with AllOrNone as false  By default, the allOrNone parameter is true

allOrNone specifies the operation allows partial success in database methods. We have to pass Boolean value to it.

If it is true then an exception is thrown if method is not successful and if set to false, remainder of failed DML can still succeed.

allOrNone parameter is used to permit whenever a Database Method is partial success  and it include a Boolean Values.

if return true, an exception is thrown which means method is failed.


No comments: