Website Loading ....

Scenarioes to use future class in salesforce

2 min read

Below are the common scenarios to use future class in salesforce :

A future method runs in the background. it is asynchronous. It is mainly used for long-running operations.

Future class Basics and limitations: Click Here

Disadvantages of Future class: Click Here

A benefit of using future methods is that some governor limits are higher, such as SOQL query limits and heap size limits.

These are the scenarios to use in future class :

  1. Mass data updates
  2. Sending email notifications
  3. connecting with external systems
  4. Generating complex reports
  5. Avoid the CPU time limit
  6. Callout from Trigger
  7. Avoid Mixed DML operations

Mass Data Update: Use the Future class for updating a large number of records to avoid timeouts and performance issues.

Sending Email Notifications: To send a large number of email notifications to users without impacting user experience.

Connecting with External Systems: Integrating with external systems is sometimes slow and unreliable so use future classes to avoid these.

Complex Reports: Generating reports which have complex calculations and huge data.

Avoid CPU time limit: As per salesforce governor limits, Limits are different for synchronous and Asynchronous. below are the few governor limits that are more for the asynchronous apex.

  • Total number of SOQL queries issues: 200
  • Total heap size: 12 MB
  • Maximum CPU time on server: 60,000 milliseconds

Callout from trigger: callouts are used to make HTTP requests to external web services. You can use callouts from a trigger to perform actions such as sending data to a third-party system or retrieving data from an external system.

Avoid Mixed DML operations : it will throw Mixed DML exceptions because of using user and Role in the same method so it will give mixed DML Exceptions. to avoid this exception future classes will be used.

public class MIxedDMLException {
@future
public static void insertUserWithRole(
String uname, String alias, String email, 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 = alias, email=email,
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;
}
}

 

Sruvi IT

Sruvi IT Solutions

Expert in digital transformation, SEO, and enterprise technology. Helping businesses grow through innovative IT solutions since 2018.