0% found this document useful (0 votes)
27 views7 pages

Trigger

Uploaded by

oemail403
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views7 pages

Trigger

Uploaded by

oemail403
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Asynchronous Processes in Salesforce

Introduction
Asynchronous processes in Salesforce allow for the execution of operations in the background
without blocking the user interface or holding up the execution of other operations. This is
especially useful for time-consuming operations such as callouts to external systems, complex
calculations, and processing large volumes of data.

Comparison Table

Type Key Features Use Case Limitations

Future Simple to implement, supports Making callouts to Cannot be monitored,


Methods callouts, limited to primitive external web services limited to 50 future
data types or collections of calls per transaction
primitives

Batch Processes large volumes of Mass data Can take longer to


Apex data, allows for query locator, processing like data execute due to large
can process up to 50 million cleansing or updates data volumes
records

Queueable Supports complex data types, Chaining multiple Limited to 50 jobs


Apex allows job chaining, can be jobs, handling added to the queue
monitored and provides better complex business per transaction
control over job execution logic

Scheduled Allows scheduling of jobs at Daily or weekly batch Limited to 100


Apex specific times, useful for processing, regular scheduled Apex jobs
periodic tasks data maintenance
Asynchronous Processes in Salesforce

Types of Asynchronous Processes

1. Future Methods:
Future methods run asynchronously and are typically used for callouts to external web services
or operations that need to be processed in the background.

Real-Time Example: Updating Account Data After a Callout


Imagine you need to make a callout to an external system to fetch the latest credit rating for a
list of accounts and update the Account records in Salesforce.

public class AccountCreditRatingUpdater {


@future(callout=true)
public static void updateCreditRatings(List<Id> accountIds) {
// Make callout to external system to get credit ratings
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/creditRatings');
req.setMethod('GET');
HttpResponse res = new Http().send(req);

// Process the response and update Account records


if (res.getStatusCode() == 200) {
// Parse the response and update accounts
List<Account> accountsToUpdate = new List<Account>();
// Assume response is a JSON array of account credit ratings
List<Object> creditRatings = (List<Object>) JSON.deserializeUntyped(res.getBody());
for (Object obj : creditRatings) {
Map<String, Object> ratingData = (Map<String, Object>) obj;
Account acc = new Account();
acc.Id = (Id) ratingData.get('accountId');
acc.Credit_Rating__c = (String) ratingData.get('creditRating');
accountsToUpdate.add(acc);
}
update accountsToUpdate;
}
}
}
Asynchronous Processes in Salesforce

Questions
1. How would you use a future method to make a callout to update a custom object with external
weather data?
2. Describe how you would fetch exchange rates from an external service and update
Opportunity records using a future method.
3. Explain how to use a future method to send data from Salesforce to an external system for
order processing.
4. How can you utilize a future method to retrieve social media metrics for a list of accounts and
update them in Salesforce?
5. Create a future method to update contact records with the latest email validation status from
an external service.
6. Explain how to handle exceptions in a future method that makes a callout to an external API.
7. How would you schedule a future method call to ensure it's run during non-peak hours?
8. Describe how to use a future method to update Salesforce records based on the response
from an external payment gateway.
9. How can you manage governor limits when making multiple callouts in a future method?
10. Explain how you would test a future method that involves making a callout to an external
system.

2. Batch Apex:

Batch Apex is used to process large volumes of records by breaking the process into
manageable chunks. It can process up to 50 million records.

Real-Time Example: Mass Updating Account Names Post Data Migration


After migrating a large number of account records into Salesforce, you need to update these
records to append a suffix to their names to signify they were migrated.

public class UpdateAccountNamesBatch implements Database.Batchable<SObject> {


public Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator('SELECT Id, Name FROM Account');
}

public void execute(Database.BatchableContext BC, List<Account> scope) {


for (Account acc : scope) {
acc.Name = acc.Name + ' - Migrated';
}
update scope;
}

public void finish(Database.BatchableContext BC) {


// Logic to execute after batch completes
Asynchronous Processes in Salesforce

}
}

// Schedule the Batch Apex job


UpdateAccountNamesBatch batch = new UpdateAccountNamesBatch();
Database.executeBatch(batch, 200); // Batch size of 200 records

Questions
1. How would you use Batch Apex to delete old records that are no longer needed in the
system?
2. Describe how you can use Batch Apex to perform complex calculations on large data sets
and update records.
3. Explain how to implement a Batch Apex job that processes a large number of leads and
updates their status based on certain criteria.
4. How can you use Batch Apex to archive records in a custom object?
5. Create a Batch Apex class to reassign ownership of accounts to a different user based on
certain conditions.
6. Describe how to chain multiple Batch Apex jobs to ensure a sequence of operations is
performed on a large data set.
7. How would you handle batch job failures and ensure records are not left in an inconsistent
state?
8. Explain how to optimize a Batch Apex job for performance.
9. Describe how you can use Batch Apex to process records in smaller chunks and handle
governor limits.
10. How would you test a Batch Apex class to ensure it processes records correctly?

3. Queueable Apex:
Queueable Apex is similar to future methods but with additional features like job chaining and
handling more complex data types.

Real-Time Example: Chain Job for Processing Orders


You need to process a large number of orders, update their status, and then send notifications
once the processing is complete.

public class ProcessOrdersQueueable implements Queueable {


public void execute(QueueableContext context) {
// Fetch orders and update their status
List<Order> orders = [SELECT Id, Status FROM Order WHERE Status = 'Pending'];
for (Order ord : orders) {
Asynchronous Processes in Salesforce

ord.Status = 'Processed';
}
update orders;

// Chain another job to send notifications


System.enqueueJob(new SendNotificationsQueueable(orders));
}
}

public class SendNotificationsQueueable implements Queueable {


private List<Order> orders;

public SendNotificationsQueueable(List<Order> orders) {


this.orders = orders;
}

public void execute(QueueableContext context) {


// Send notifications for processed orders
for (Order ord : orders) {
// Send notification logic here
}
}
}

// Enqueue the initial job


System.enqueueJob(new ProcessOrdersQueueable());

Questions
1. How would you use Queueable Apex to process complex data transformations on a large set
of records?
2. Describe how to chain multiple Queueable Apex jobs to perform sequential operations on a
data set.
3. Explain how you can use Queueable Apex to handle callouts that require complex data
structures.
4. How can you monitor the execution of Queueable Apex jobs and handle job failures?
5. Create an Queueable Apex class to update contact records based on external data fetched
via callouts.
6. Describe how you can use Queueable Apex to handle asynchronous processing of case
records and notify users upon completion.
7. How would you implement a retry mechanism for failed Queueable Apex jobs?
8. Explain how to pass complex data types between chained Queueable Apex jobs.
Asynchronous Processes in Salesforce

9. Describe how you can use Queueable Apex to process records in batches and handle large
data volumes.
10. How would you test a Queueable Apex class that involves chaining multiple jobs?

4. Scheduled Apex:
Scheduled Apex allows you to schedule a class to run at specific times. This is useful for
periodic tasks like daily or weekly batch processing.

Real-Time Example: Daily Data Backup


You need to create a daily backup of certain records in Salesforce and store them in a custom
object.

public class DailyBackupJob implements Schedulable {


public void execute(SchedulableContext SC) {
// Fetch records to backup
List<Account> accounts = [SELECT Id, Name FROM Account WHERE
LastModifiedDate = LAST_N_DAYS:1];

// Create backup records


List<Backup__c> backups = new List<Backup__c>();
for (Account acc : accounts) {
Backup__c backup = new Backup__c();
backup.Account_Id__c = acc.Id;
backup.Account_Name__c = acc.Name;
backups.add(backup);
}
insert backups;
}
}

// Schedule the job to run daily at 2 AM


String cronExpression = '0 0 2 * * ?';
System.schedule('Daily Data Backup', cronExpression, new DailyBackupJob());

Questions
1. How would you schedule an Apex job to run weekly to update the status of inactive users?
2. Describe how to implement a Scheduled Apex job to send out monthly newsletters to all
contacts.

3. Explain how you can use Scheduled Apex to perform regular maintenance tasks, such as
cleaning up old data.
Asynchronous Processes in Salesforce

4. How can you ensure a Scheduled Apex job runs only on weekdays and not on weekends?
5. Create a Scheduled Apex job to generate and email reports to managers every morning.
6. Describe how to handle rescheduling of an Apex job in case of job failures.
7. How would you schedule a batch job to run at a specific time every day?
8. Explain how you can monitor the execution of Scheduled Apex jobs and handle errors.
9. Describe how to implement a Scheduled Apex job to perform daily data synchronization with
an external system.
10. How would you test a Scheduled Apex class to ensure it runs at the correct time and
performs the intended operations?

Conclusion:
Asynchronous processing in Salesforce is a powerful feature that helps improve system
performance and user experience by allowing long-running operations to be performed in the
background. Understanding the different types of asynchronous processes and their use cases
will enable you to build efficient and scalable applications on the Salesforce platform.

You might also like