Tag: Asynchronous

  • Power of Asynchronous Apex: Benefits and Insights

    Power of Asynchronous Apex: Benefits and Insights

    Introduction

    Salesforce is renowned for its ability to provide businesses with comprehensive customer relationship management (CRM) solutions. To supercharge its functionality, Salesforce introduced Asynchronous Apex, a powerful feature that enables developers to perform background processing and schedule tasks, ultimately enhancing performance and productivity. In this blog post, we’ll explore the world of Asynchronous Apex, and its benefits, and delve into some key details to help you harness its potential.

    What is Asynchronous Apex?

    Asynchronous Apex is a Salesforce feature that allows developers to execute code outside the traditional request-response model. In simpler terms, it lets you run processes in the background, freeing up resources for other tasks. This capability is especially valuable when dealing with time-consuming operations like data imports, email notifications, and data processing.

    Benefits of Asynchronous Apex

    1. Improved User Experience: Asynchronous Apex ensures that time-consuming tasks don’t block the user interface. This leads to a more responsive and seamless user experience, as users can continue working without waiting for long-running processes to complete.
    2. Scalability: By offloading tasks to the background, Asynchronous Apex enhances your Salesforce application’s scalability. It prevents resource contention and allows your system to handle an increasing number of requests without performance degradation.
    3. Enhanced Performance: Asynchronous processing optimizes resource allocation, resulting in better performance and reduced execution time for critical operations.
    4. Robust Error Handling: Asynchronous Apex provides robust error handling mechanisms. It can automatically retry failed jobs, send notifications, and log errors for easy troubleshooting.
    5. Bulk Data Processing: Salesforce bulk data operations like data imports, updates, and deletions can be resource-intensive. Asynchronous Apex is particularly beneficial for handling large volumes of data efficiently.

    Types of Asynchronous Apex

    Salesforce offers different ways to implement asynchronous processing:

    Batch Apex: Batch Apex is suitable for processing large datasets efficiently. It divides a large job into smaller, manageable chunks, making it easier to handle.

    Example: Updating Contact Records

    public class UpdateContactsBatch implements Database.Batchable<SObject> {
        public Database.QueryLocator start(Database.BatchableContext context) {
            return Database.getQueryLocator('SELECT Id, FirstName, LastName FROM Contact WHERE LastModifiedDate < LAST_N_DAYS:30');
        }
        public void execute(Database.BatchableContext context, List<Contact> scope) {
            // Update the contact records
            for (Contact con : scope) {
                con.FirstName = 'Updated';
                con.LastName = 'Contact';
            }
            update scope;
        }
        public void finish(Database.BatchableContext context) {
            // Perform any post-processing tasks
        }
    }

    Queueable Apex: Queueable Apex is used to schedule and prioritize background jobs. It’s perfect for scenarios where you want to control the order of execution or pause/resume processing.

    Example: Sending Email Notifications

    public class EmailNotificationQueueable implements Queueable {
        String recipient;
        String message;
        public EmailNotificationQueueable(String recipient, String message) {
            this.recipient = recipient;
            this.message = message;
        }
        public void execute(QueueableContext context) {
            // Send an email to the recipient
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setToAddresses(new List<String>{recipient});
            email.setSubject('Notification');
            email.setPlainTextBody(message);
            Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
        }
    }

    Scheduled Apex: Scheduled Apex lets you schedule classes to run at specific times or on a recurring basis. It’s ideal for automating routine tasks, such as generating reports or sending email notifications.

    dont miss out iconDon’t forget to check out: Here’s All you need to Know About Asynchronous Apex in Salesforce

    Example: Send an email using a Schedulable class

    global class EmailSenderScheduled implements Schedulable {
        global void execute(SchedulableContext ctx) {
            // Define the email details
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setToAddresses(new String[]{'recipient@example.com'});
            mail.setSubject('Scheduled Email');
            mail.setPlainTextBody('This is a scheduled email sent from Salesforce.');
            // Send the email
            List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
            emails.add(mail);
            Messaging.sendEmail(emails);
        }
    }

    Future Methods: Future methods allow you to run code asynchronously when resources are available. They’re commonly used for one-off tasks that need to be completed in the background.

    public class EmailSender {
        @future
        public static void sendEmail(String recipient, String subject, String body) {
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setToAddresses(new String[]{recipient});
            email.setSubject(subject);
            email.setPlainTextBody(body);
            try {
                Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
            } catch (Exception e) {
                System.debug('Email sending failed: ' + e.getMessage());
            }
        }
    }

    Considerations and Best Practices

    While Asynchronous Apex offers many benefits, it’s essential to use it judiciously and follow best practices to avoid potential pitfalls:

    1. Governance Limits: Salesforce enforces governor limits for Asynchronous Apex. Be aware of these limits to ensure smooth execution.
    2. Bulk Data Handling: When working with bulk data, consider batch processing or Queueable Apex to prevent hitting governor limits.
    3. Logging and Monitoring: Implement robust error handling, logging, and monitoring to track the progress and health of your asynchronous jobs.
    4. Optimize Code: Write efficient code to minimize execution time and resource consumption.

    Key Benefits of Asynchronous

    1. Improved User Experience:
      • Asynchronous Apex allows time-consuming processes to run in the background, preventing them from blocking the user interface.
      • Users can continue using the application without waiting for resource-intensive tasks to complete, leading to a more responsive and seamless experience.
    2. Scalability:
      • By offloading tasks to the background, Asynchronous Apex improves the scalability of Salesforce applications.
      • It prevents resource contention and allows the system to handle a higher volume of requests without performance degradation.
    3. Enhanced Performance:
      • Asynchronous processing optimizes resource allocation by running tasks when resources are available.
      • This leads to improved overall system performance and reduced execution time for critical operations.
    4. Bulk Data Processing:
      • Asynchronous Apex is particularly beneficial for handling large volumes of data efficiently.
      • It enables developers to divide data processing tasks into smaller, manageable chunks, reducing the risk of hitting governor limits.
    5. Scheduled Automation:
      • Scheduled Apex allows developers to automate routine tasks on a predefined schedule.
      • This is useful for generating reports, sending email notifications, or performing other periodic actions without manual intervention.
    6. Robust Error Handling:
      • Asynchronous Apex provides mechanisms for handling errors and exceptions effectively.
      • It can automatically retry failed jobs, send notifications, and log errors for easy troubleshooting and maintenance.
    7. Batch Processing:
      • Batch Apex allows developers to process data in chunks, making it suitable for tasks like data imports, updates, and transformations.
      • It helps avoid hitting governor limits that apply to synchronous operations.
    8. Reduced Execution Time:
      • By executing tasks in the background, Asynchronous Apex reduces the time it takes to complete complex operations.
      • This leads to faster response times and improved overall system performance.

    dont miss out iconCheck out another amazing blog by Aman here: Salesforce Formula Practice Questions | The Ultimate Guide

    Conclusion

    Asynchronous Apex is a game-changer for Salesforce developers and administrators. Its ability to run processes in the background, improve user experience, enhance scalability, and optimize performance makes it an invaluable tool for building efficient and responsive Salesforce applications. By understanding the different types of Asynchronous Apex and following best practices, you can harness its full potential and take your CRM to the next level.

    I hope you like this blog and if you want any help let me know in the comment section.

    Stay tuned, there is way more to come! Follow me on LinkedIn, Instagram, and Twitter. So you won’t miss out on all future articles.

  • Learn About All the Different Interfaces in Salesforce Apex Class

    Learn About All the Different Interfaces in Salesforce Apex Class

    Need for @future Methods  

    @future need resources for a longer time to make an API callout, an external web service to perform bulk data operation (batch apex) 

    Governer limits to avoid mixed DML operation.

    execute:class name.method name  

    database.batchable== interface 

    start,execute,finish 

    database.batchableContext== 

    grtJobId,getChildJobId() 

    dont miss out iconDon’t forget to check out: Salesforce Apex Tutorial for beginners | Apex Salesforce Tutorial

    SETUP OBJECTS: ex-userRole, if changes are made on u, u r going to affect the permissions on the database

    NON-SETUP OBJECTS: ex-account, no impact on permissions within a single method, you cannot create setup and non-setup objects in a single transaction for knowing status  

    list<asyncapexjob> jobs=[select id,status,Jobtype from AsyncApexJob]; 

    50 future method queue can be called within a queue but a future cannot be called within a future.sequence with asynchronous process chaing of job available in the queue. 

    Support sObjects gives record id, the id of the job  

    Database.stateful interface 

    In Batch apex Changes made by one execute do not transfer to the other execute, so we need to implement “Database.Stateful” if the batch process needs information that is shared across transactions. 

    In other words, If you want to transfer the state of the data from one batch to another batch we need to implement “Database.Stateful” interface. 

    If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions. Maintaining state is useful for counting or summarizing records as they’re processed. For example, suppose your job processed opportunity records. You could define a method in execute to aggregate totals of the opportunity amounts as they were processed. 

    If you don’t specify Database.Stateful, all static and instance member variables are set back to their original values. 

    To use Batch Apex, we must implement Database.Batchable interface, below are the methods which we use: 

    1. Start 
    2. Execute 
    3. Finish 

    dont miss out iconCheck out anther amazing blog by Navdita here: Multi-Factor Authentication in Salesforce – A Short Guide

    Start:

    This method is called at the beginning of the batch apex job. This method will return either an object or type Database.QueryLocator or an iterable that contains the records or objects passed to the job. This method will collect records on which the operation will be performed.  

    These records are divided into batches and passed to execute method. 

    Execute:

    This method contains the set of instructions which we want to perform on those records which we retrieved from the Start method.        

    Finish:

    This method gets executed after all the batches are processed. We use this method to send emails to inform them about the job completion. 

    Below is an example: 

    global class AccountBatchUpdate implements Database.Batchable<sObject> 
    { 
        global Database.QueryLocator start(Database.BatchableContext BC) 
        { 
            String query = ‘SELECT Id,Name FROM Account’; 
            return Database.getQueryLocator(query); 
        } 
       global void execute(Database.BatchableContext BC, List<Account> scope) 
        { 
           for(Account a : scope) 
           { 
               a.Name = a.Name + ‘******’; 
           } 
           update scope; 
       }  
       global void finish(Database.BatchableContext BC) { } 
    }
  • Salesforce Chatter vs Slack – A Comparative Analysis

    Salesforce Chatter vs Slack – A Comparative Analysis

    As part of its strategic acquisition policy, Salesforce surprised the world with the billion-dollar acquisition of Slack Technologies Inc. In the words of Marc Benioff, President and CEO of Salesforce, “Together we’ll define the future of enterprise software, creating the digital HQ that enables every organization to deliver customer and employee success from anywhere”.

    However, with this acquisition, one question was left unanswered: what are the future of Chatter for the Salesforce platform and its customers? Until now, Chatter was the enterprise collaboration software for CRM. So why would billions be spent on Slack, a tool with similar functionality to Chatter? Below, we highlight several points to help you understand this decision by Salesforce.

    Asynchronous Communication vs. Real-time Communication

    Chatter is more than a collaborative tool, it is an internal Salesforce communication and notification tool. It is asynchronous by nature, as its greatest strength is the ability to share information within the CRM’s own records. Its fundamental support is email, which makes it more functional for one-to-many communications, but not for conversational collaboration. Slack, on the other hand, operates in real-time and relies heavily on users being online. In addition, it allows you to create private or group channels, as well as attach voice notes, videos and other files. Users of paid plans can meet using Huddle, a feature of Slack with much potentialities. With this, you can have an informal discussion or meeting by voice communication, just like in the office. Groups can have up to 50 participants and have the option to share screens and enable live captions.

    dont miss out iconDon’t forget to check out: Understanding Salesforce Chatter and Its Implementation

    Modalities of Prices and Accessibility

    chatter vs slack

    Chatter vs Slack, Who Uses Them?

    Chatter was developed primarily to be used by sales, marketing, service teams, as well as general project collaboration. Also, it works only within the Salesforce ecosystem and its users. This means if the entire company isn’t linked to the CRM, it’s considerably laborious to bring people from other teams on board and achieve effective collaboration. Even for exclusive Chatter members, the functionality is extremely limited and they still have to work through a Salesforce user interface. In contrast, Slack is generally adopted by the entire company. This is key for business collaboration, as no matter what your team is, any worker can have a productive and rewarding experience using this platform.

    Integration

    Slack was designed for easy integration with other systems and is backed by over 1,500 built-in apps with a robust set of APIs for creating custom connectors. In contrast, Chatter has a very limited set of connectors, as it was designed to be used within the Salesforce ecosystem.

    dont miss out iconCheck out another amazing blog by SkyPlanner here: Our Top 5 Preferred Tools for Salesforce Data Migration

    Mobile versions

    Chatter doesn’t have a good reputation for its mobile interface while Slack works seamlessly on any smart device and provides one of the best user experiences on the market. With Slack mobile, you can do just about anything you’d expect with your web or desktop apps. This functionality enhances real-time communication, since it is useful to start a conversation with a client on the move, during fieldwork, or remotely.

    With an eye to the future and given its respective features and potential, Slack has the makings to become Salesforce’s new collaborative participation and interaction software of choice.

  • Batch Apex in Salesforce (Basics, Governor Limits, Custom Iterable of Batch)

    Batch Apex in Salesforce (Basics, Governor Limits, Custom Iterable of Batch)

    Transaction limits in APEX

    • Absolute number of SOQL queries issued 1 – 100 
    • Absolute number of records recovered by SOQL queries- 50,000 
    • Absolute number of records recovered by Database.getQueryLocator – 10,000 
    • Absolute number of records recovered by a SOSL inquiry – 2,000 
    • Absolute number of DML issued 2 – 150 
    • Absolute number of records handled because of DML proclamations, Approval process, or database.emptyRecycleBin – 10000 
    • Complete number of callouts (HTTP demands or Web administrations calls) in an exchange – 100 
    • Most extreme aggregate break for all callouts (HTTP demands or Web administrations calls) in an exchange – 120 
    • The most extreme number of techniques with the future explanation permitted per Apex summon – 50 
    • Greatest number of Apex occupations added to the line with System.enqueueJob – 50 
    • Absolute number of sendEmail strategies permitted – 10 
    • Most extreme execution time for every Apex exchange – 10 least 
    • Most extreme number of pop-up message strategy calls permitted per Apex exchange – 10 
    • Most extreme number of message pop-ups that can be sent in each message pop-up technique call – 2000

    Database.Batchable Interface

    To utilize batch Apex, compose an Apex class that executes the Salesforce-gave interface Database.Batchable and afterward summon the class automatically. 

    To stop the execution of the Batch Apex work, Go to Setup and enter Apex Jobs in the Quick Find box, and select Apex Jobs. 

    dont miss out iconDon’t forget to check out: Concept of Virtual and Abstract Modifiers in Apex | Salesforce Developer Guide

    Method in Batchable Interface

    • Start() 
    • Execute() 
    • Finish() 

    Batch Apex in Salesforce is uncommonly intended for an enormous number of records, i.e., here, information would be isolated into little clumps of records, and afterward, it would be assessed. All in all, the Batch class in Salesforce is explicitly intended to handle mass records together and have a more prominent lead representative breaking point than the simultaneous code. 

    Start: This strategy is called at the beginning of a batch task to gather the information on which the Batch job will be working. It breaks the information or record into batches. Now and again, the ‘QueryLocator‘ technique is utilized to work with the basic SOQL query to generate the scope of objects inside a batch job. 

    Asynchronous operations can be carried out by Batch Apex classes

    Batch occupations are invoked programmatically during the runtime and can be worked on any size of records, with a limit of 200 records for each clump. You can separate bigger record information into 200 records for each clump to execute it better.

    Database.QueryLocator

    With the QueryLocator object, the lead agent cutoff for unquestionably the quantity of records recuperated by SOQL requests is evaded and you can address up to 50 million records.

    In any case, with an Iterable, the lead agent limit for without a doubt the quantity of records recuperated by SOQL requests is at this point approved. 

    QueryLocator object or an Iterable that contains the records or items passed to the work.

    Custom Iterable

    The iterator technique should be proclaimed as worldwide or public.

    In the accompanying model a custom iterator emphasizes through an assortment:

    global class Iterables
    implements Iterator<Contact>{
        List<Contact> con{get; set;}
        Integer i {get; set;}
        public Iterables(){
            con=
            [SELECT Id, Name,
            NumberOfEmployees
            FROM Contact
            WHERE Name = 'false'];
            i = 0;
        } 
        global boolean hasNext(){
            if(i >= con.size()) {
                return false;
            } else {
                return true;
            }
        }   
        global Contact next(){
            // 8 is an arbitrary
            // constant in this example
            // that represents the
            // maximum size of the list.
            if(i == 8){return null;}
            i++;
            return con[i-1];
        }
    }
    global class example implements iterable<contact>{
        global Iterator<Contact> Iterator(){
            return new Iterables();
        }
    }
    global class batchClass implements Database.batchable<Contact>{
        global Iterable<Contact> start(Database.batchableContext info){
            return new example();
        }   
        global void execute(Database.batchableContext info, List<Contact> scope){
            List<Contact> conToUpdate = new List<Contact>();
            for(Contact a : scope){
                a.Name = 'true';
                a.NumberOfEmployees = 69;
                conToUpdate.add(a);
            }
            update conToUpdate;
        }   
        global void finish(Database.batchableContext info){}
    }

    dont miss out iconCheck out another amazing blog by Ratnesh here: Preparation for Unplanned Downtime in Salesforce

    Execute Method

    Used to gather the records of objects to be passed to the interface methods executed for preparing. 

    This technique is called once toward the start of a Batch Apex work and returns either a Database.QueryLocator object or an Iterable that contains the records or articles passed to the job.