Tag: Queueable Apex

  • 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.

  • Interview Question Part – 3

    Interview Question Part – 3

    1. What is an Apex class in Salesforce?

    An Apex class in Salesforce is a blueprint or template for creating custom business logic and functionality. It is written in the Apex programming language, which is similar to Java, and is used to define the behavior of objects in the Salesforce platform.

    2. Explain the syntax of creating an Apex class.

    The syntax for creating an Apex class is as follows:

    public class ClassName { 
    // Class variables, properties, and methods 
    }

    The keyword “public” denotes the access level of the class, and it can be either public or private. The class name follows the “class” keyword, and the body of the class is enclosed within curly braces.

    3. What is the difference between a standard controller and a custom controller?

    A standard controller is a pre-built controller provided by Salesforce for standard objects like Account, Contact, or Opportunity. It provides basic functionality and automatically handles most of the operations related to data retrieval, manipulation, and standard page actions.

    On the other hand, a custom controller is a controller that you create to define custom logic and behavior for a Visualforce page or a Lightning component. It allows you to implement custom business processes and extend functionality beyond what is provided by the standard controller.

    4. How can you define a method in an Apex class?

    public returnType methodName(parameterList) { 
    // Method body 
    }

    5. What is the purpose of the “public” and “private” access modifiers in Apex?

    The “public” and “private” access modifiers in Apex control the visibility and accessibility of variables and methods within a class.

    1. public” means that the variable or method can be accessed from outside the class.
    2. private” means that the variable or method can only be accessed within the class itself.

    By using these access modifiers, you can define the level of encapsulation and control the interaction with the class’s internal members.

    dont miss out iconDon’t forget to check out: Are You Here To Know Reasons To Hire Salesforce Developer For Your Business?

    6. Explain the difference between “static” and “instance” methods in Apex.

    In Apex, the “static” keyword is used to define a method or variable that belongs to the class itself rather than an instance of the class. It means that the method or variable can be accessed without creating an instance of the class.

    On the other hand, an “instance” method is a method that operates on a specific instance of a class. It requires an object of the class to be created, and the method is invoked on that object.

    “static” methods or variables are associated with the class itself, while “instance” methods or variables are associated with individual instances of the class.

    7. How do you define a variable in Apex? What are the different data types available?

    In Apex, you can define a variable using the following syntax:

    dataType variableName [= initialValue];

    The dataType specifies the type of data that the variable can hold, and the variableName is the name you give to the variable. The “= initialValue” part is optional and is used to assign an initial value to the variable.

    Apex supports various data types, including primitives like Integer, Boolean, and String, as well as complex types like sObjects, lists, and maps.

    8. How can you implement exception handling in Apex?

    Ans. Exception handling in Apex allows you to catch and handle errors or exceptional situations that may occur during the execution of your code. You can implement exception handling using try-catch blocks.

    try { 
    // Code that may throw an exception 
    } 
    catch (ExceptionType e) { 
    // Code to handle the exception 
    }

    Inside the try block, you place the code that may throw an exception. If an exception occurs, it is caught by the catch block, where you can handle the exception appropriately. The “ExceptionType” specifies the type of exception you want to catch.

    You can use “finally” blocks to specify code that should be executed regardless of whether an exception is thrown or not.

    9. Explain the difference between a trigger and an Apex class.

    A trigger is an Apex code that is executed before or after specific data manipulation operations, such as insert, update, delete, or undelete, on Salesforce objects. Triggers are used to enforce data integrity, perform additional logic, or update related records based on certain conditions.

    On the other hand, an Apex class is a general-purpose class that can be written to encapsulate business logic and reusable functionality. It can be invoked from various contexts like triggers, Visualforce pages, or Lightning components.

    In summary, a trigger is specific to a particular object and is automatically executed based on data manipulation events, while an Apex class is a reusable piece of code that can be invoked from multiple contexts.

    10. How can you write a test class for an Apex class? What is the purpose of test classes?

    To write a test class for an Apex class, you create a separate class in Salesforce that contains test methods. Test classes are used to verify that your code works as expected and to achieve code coverage, which is a requirement for deploying Apex code to production.

    The purpose of test classes is to simulate different scenarios and assert the expected outcomes. They help ensure that the code is functioning correctly and prevent regressions when making changes.

    Test classes follow a naming convention and are annotated with the @isTest annotation. Inside the test class, you write methods with the @isTest annotation to define test methods.

    11. What are the best practices for writing efficient Apex code?

    Best practices for writing efficient Apex code include:

    1. Bulkify your code: Design your code to process data in bulk to avoid hitting governor limits and improve performance.
    2. Use selective queries: Query only the necessary data to minimize database operations and optimize performance.
    3. Minimize SOQL and DML statements: Reduce the number of queries and updates to conserve resources.
    4. Avoid nested loops: Nested loops can result in poor performance. Use collections and efficient algorithms to avoid nested loops whenever possible.
    5. Cache frequently accessed data: Store frequently accessed data in memory for faster access and reduced database calls.
    6. Handle exceptions gracefully: Implement proper exception handling to handle errors and prevent unhandled exceptions from impacting the user experience.
    7. Follow naming conventions: Use clear and descriptive names for variables, classes, and methods to enhance code readability.
    8. Use governor limit-aware coding: Be aware of the Salesforce governor limits and design your code to stay within those limits.
    9. Write comprehensive unit tests: Ensure that your code is thoroughly tested to catch any issues early and maintain code quality.

    12. How can you query records from the database using SOQL in Apex?

    SOQL (Salesforce Object Query Language) is used to query records from the database in Salesforce. In Apex, you can use SOQL statements to retrieve records based on specified conditions.

    The basic syntax for a SOQL query in Apex is as follows:

    List<SObject> records = [SELECT field1, field2 FROM ObjectName WHERE condition];

    1. “List<SObject>” defines the variable to store the query results.
    2. “SELECT field1, field2” specifies the fields to retrieve from the object.
    3. “FROM ObjectName” specifies the object to query.
    4. “WHERE condition” filters the records based on specified conditions.

    You can also use additional clauses like ORDER BY, LIMIT, and OFFSET to further refine your queries.

    13. What is the purpose of DML statements in Apex? Give examples of different DML operations.

    DML (Data Manipulation Language) statements in Apex are used to perform CRUD (Create, Read, Update, Delete) operations on records in the database.
    Some examples of DML operations in Apex are:

    Inserting a Record:

    ObjectName record = new ObjectName(field1 = value1, field2 = value2); 
    insert record;

    Updating a Record:

    ObjectName record = [SELECT field1, field2 FROM ObjectName WHERE Id = 'recordId']; 
    record.field1 = newValue;
    update record;

    Deleting a Record:

    ObjectName record = [SELECT field1, field2 FROM ObjectName WHERE Id = 'recordId']; 
    delete record;

    DML statements are used to interact with the database and modify record data.

    14. How do you enforce sharing rules in an Apex class?

    Sharing rules in Salesforce determine the level of access users have to records. In an Apex class, you can enforce sharing rules by using the “with sharing” keyword.

    By default, Apex classes run in system mode, which ignores the organization’s sharing rules. However, when you specify “with sharing” in the class definition, the class runs in user mode, respecting the sharing rules.

    This means that the code inside the class will honor the record-level access permissions and sharing settings defined by the organization’s sharing rules, profiles, and sharing settings.

    Enforcing sharing rules ensures that the Apex class operates within the defined access controls, providing the appropriate level of record visibility and security.

    15. Explain the difference between a constructor and a method in Apex.

    Ans. In Apex, a constructor is a special method used to initialize the object of a class. It is invoked when an object is created using the “new” keyword. Constructors have the same name as the class and do not specify a return type.

    public class MyClass { 
        public MyClass() { 
             // Constructor logic 
        } 
    }

    On the other hand, a method is a block of code that performs a specific action. Methods are used to encapsulate reusable functionality within a class. They can accept input parameters, execute a series of statements, and optionally return a value.

    The main difference between a constructor and a method is that a constructor is automatically invoked when an object is created, whereas a method is called explicitly by the code.

    16. What is the “with sharing” keyword in Apex? How does it impact record visibility?

    Ans. The “with sharing” keyword in Apex is used to enforce record-level access permissions and sharing rules in a class. When a class is declared with “with sharing,” it runs in user mode and respects the organization’s sharing rules.

    The “with sharing” keyword affects the visibility of records based on the user’s access permissions, profile settings, and sharing rules. It ensures that the code in the class only works with the records that the user has proper access to, providing a secure and controlled environment.

    By default, Apex classes run in system mode, which ignores sharing rules. However, when “with sharing” is specified, the class operates in user mode and respects the sharing settings.

    17. How can you schedule Apex classes to run at specific times?

    Ans. You can schedule Apex classes to run at specific times using the Schedulable interface in Apex. The Schedulable interface allows you to define a class as a scheduled job that can be executed according to a specified schedule.

    To schedule an Apex class, you need to implement the Schedulable interface and define the schedule using the System.schedule method.

    Here’s an example of scheduling an Apex class to run every day at a specific time:

    public class MyScheduledClass implements Schedulable { 
         public void execute(SchedulableContext context) { 
         // Logic to be executed on schedule 
         } 
    } 
    // Schedule the Apex class to run every day at 8 AM String cronExp = '0 0 8 * * ?'; 
    String jobName = 'MyScheduledJob'; System.schedule(jobName, cronExp, new MyScheduledClass());

    This code schedules the MyScheduledClass to run every day at 8 AM based on the specified cron expression.

    18. What is the purpose of the “Database” class in Apex?

    Ans. The “Database” class in Apex provides methods to perform database operations like insert, update, upsert, delete, and query records. It also allows you to interact with records in bulk and handle governor limits.

    Some common use cases for the “Database” class include:

    1. Performing DML operations on records in bulk.
    2. Querying records with dynamic SOQL queries.
    3. Inserting or updating records while bypassing triggers.
    4. Handling partial success and DML exceptions.
    5. Retrieving the ID of the inserted or updated record.

    The “Database” class provides additional capabilities beyond the standard DML statements and is useful for advanced database operations in Apex.

    19. How can you implement asynchronous processing in Apex?

    Ans. Asynchronous processing in Apex allows you to execute code in the background without blocking the user interface or other operations. It helps improve performance and provides a way to handle long-running or resource-intensive tasks.

    To implement asynchronous processing, you can use features like future methods, batch Apex, and queueable Apex.

    1. Future methods: They are annotated with the @future annotation and allow you to execute a method asynchronously. The method is queued for execution and runs in a separate thread.
    2. Batch Apex: It allows you to process large sets of data in smaller chunks or batches. Batch Apex jobs are divided into multiple batches, and each batch is processed independently.
    3. Queueable Apex: It allows you to chain and schedule the execution of jobs. Each job is added to a queue and executed in sequence, providing flexibility and control over the execution order.

    These asynchronous processing methods help handle time-consuming tasks, integrate with external systems, and perform complex operations in a scalable manner.

    20. Explain the concept of batch Apex and its use cases

    Ans. Batch Apex is a feature in Salesforce that allows you to process large sets of data asynchronously in smaller chunks or batches. It is useful when dealing with large data volumes that exceed the normal governor limits.

    Batch Apex jobs are divided into multiple batches, and each batch can process a subset of the data. The data is processed in a batch-by-batch manner, and the results can be collected and processed after each batch or at the end of the job.

    Batch Apex jobs follow a specific pattern:

    1. Start method: It collects the initial set of records to be processed and sets up the batch job.
    2. Execute method: It processes each batch of records and performs the required operations.
    3. Finish method: It handles any post-processing tasks after all batches have been executed.

    Batch Apex is useful for data transformation, data migration, complex calculations, and other scenarios where large volumes of data need to be processed efficiently.

    21. What are governor limits in Apex? How do they impact the execution of code?

    Ans. Governor limits in Apex are runtime limits set by Salesforce to ensure the efficient and fair use of shared resources. They restrict the number of resources a transaction or code execution can consume, such as CPU time, heap size, database queries, and DML operations.

    Governor limits impact the execution of code by enforcing certain boundaries to prevent abuse, optimize performance, and maintain system stability. If a transaction or code execution exceeds the limits, it results in a runtime exception.

    Developers need to be mindful of governor limits when writing Apex code to avoid hitting limits and ensure the code performs optimally.

    Examples of governor limits include:

    1. CPU time limit: Specifies the maximum amount of CPU time a transaction can use.
    2. Query rows limit: Restricts the number of records that can be returned in a single query.
    3. Heap size limit: This limits the amount of memory a transaction can use.
    4. DML statements limit Limits the number of records that can be inserted, updated, or deleted in a single transaction.

    Understanding and optimizing code to stay within governor limits is crucial for maintaining a scalable and efficient Salesforce application.

    22. How can you implement triggers in Apex? What are the different trigger events available?

    Ans. Triggers in Apex are pieces of code that execute before or after specific data manipulation operations, such as insert, update, delete, or undelete, on Salesforce objects. They are used to enforce data integrity, perform additional logic, or update related records based on certain conditions.

    To implement triggers, you define trigger handlers that contain the logic to be executed when a trigger event occurs. Trigger handlers can be written as separate classes or as methods within the trigger itself.

    Trigger events include:

    1. before insert: Triggered before records are inserted.
    2. before update: Triggered before records are updated.
    3. before delete: Triggered before records are deleted.
    4. after insert: Triggered after records are inserted.
    5. after update: Triggered after records are updated.
    6. after delete: Triggered after records are deleted.
    7. after undelete: Triggered after records are undeleted.

    By using triggers, you can automate processes, maintain data integrity, and extend the functionality of Salesforce objects.

    dont miss out iconCheck out another amazing blog by Aman here: Mule Dreamin: Shaping MuleSoft+Salesforce Together for a Powerful Integration

    23. Explain the difference between a before trigger and an after trigger.

    Ans. Before triggers and after triggers are types of triggers in Apex that determine when the trigger logic is executed in relation to the data manipulation operation.

    1. Before triggers: They are executed before the data manipulation operation occurs. Before triggers are used to perform validation or modification on the records before they are saved to the database. They are commonly used to enforce business rules and validate data.
    2. After triggers: They are executed after the data manipulation operation occurs. After triggers are used to perform additional logic or update related records based on the changes made by the trigger operation. They can be used to update fields, create related records, or invoke external services.

    The choice between before and after triggers depends on the specific requirements of the business logic and the timing of the necessary operations.

    24. How can you implement a trigger handler class in Apex? What are the benefits of using a trigger handler pattern?

    Ans. A trigger handler class in Apex is a design pattern that separates the trigger logic from the trigger itself. It provides a structured way to handle trigger events and improves code maintainability and reusability.

    The trigger handler pattern involves creating a separate class to hold the trigger logic. The trigger itself acts as a bridge between the Salesforce platform and the trigger handler class.

    Benefits of using a trigger handler pattern include:

    1. Separation of concerns: The trigger handler class focuses solely on the trigger logic, making it easier to understand and maintain.
    2. Reusability: The same trigger handler class can be used for multiple triggers, reducing code duplication.
    3. Testability: The trigger handler class can be unit tested independently of the trigger.
    4. Scalability: The trigger handler pattern allows for easier extension and modification of trigger logic as business requirements change.

    By adopting the trigger handler pattern, you can write cleaner and more modular trigger code, leading to better code organization and easier maintenance.

    25. What is the purpose of the “Schema” class in Apex? How can you use it for dynamic SOQL and DML operations?

    Ans. The “Schema” class in Apex provides metadata information about the Salesforce objects, such as fields, relationships, and object definitions. It allows you to dynamically retrieve information about objects and fields at runtime.

    The “Schema” class provides methods to access and manipulate metadata, including:

    • getGlobalDescribe(): Returns a map of all object describe information.
    • getSObjectType(): Returns the SObjectType for a given object name.
    • getDescribe(): Returns the describe information for a specific object or field.

    You can use the “Schema” class for dynamic SOQL and DML operations, dynamic field retrieval, and generating dynamic user interfaces.

    For example, you can dynamically query fields based on user input, dynamically create or modify fields, or generate UI components based on the metadata obtained from the “Schema” class.

    26. How do you handle bulkification in Apex code? Why is it important?

    Ans. Bulkification in Apex refers to designing code that can efficiently process large sets of data. It involves writing code in a way that operates on collections of records rather than individual records, reducing the number of database queries and DML statements.

    Bulkification is important to avoid hitting governor limits and optimize code performance. By processing data in bulk, you can minimize the number of queries and updates, conserve resources, and improve overall execution speed.

    To achieve bulkification, you can follow these best practices:

    1. Query records in bulk: Use SOQL queries with proper filters and retrieve all necessary records in a single query instead of querying inside a loop.
    2. Perform DML operations in bulk: Use collections like lists and sets to hold records and perform DML operations on them outside of loops.
    3. Use collections for processing: Iterate over collections of records to perform calculations or operations, rather than processing one record at a time.
    4. Minimize SOQL and DML statements: Reduce the number of queries and updates by batching them together.

    By adopting these practices, you can ensure your code can handle large volumes of data efficiently and avoid performance issues.

    27. Explain the concept of a trigger context variable in Apex.

    Ans. In Apex, a trigger context variable is an object that provides contextual information about the trigger event being executed. It contains information such as the records involved, the operation type, and the trigger execution context.

    The trigger context variable is automatically available within a trigger and can be accessed using the Trigger keyword. It provides access to various trigger context variables, such as:

    1. Trigger.new: Returns a list of new records being inserted or updated.
    2. Trigger.old: Returns a list of old records before they were updated or deleted.
    3. Trigger.newMap: Returns a map of new records, with the record IDs as keys.
    4. Trigger.oldMap: Returns a map of old records, with the record IDs as keys.
    5. Trigger.isInsert: Indicates if the trigger event is an insert operation.
    6. Trigger.isUpdate: Indicates if the trigger event is an update operation.
    7. Trigger.isDelete: Indicates if the trigger event is a delete operation.

    By using the trigger context variables, you can access and manipulate the records involved in the trigger event and perform specific logic based on the operation type.

    28. How can you perform unit testing for triggers in Apex?

    Ans. Unit testing for triggers in Apex involves writing test classes to ensure the trigger logic behaves as expected and meets the desired requirements. Unit tests help validate the trigger functionality, test different scenarios, and identify potential issues or bugs.

    To perform unit testing for triggers, you typically follow these steps:

    1. Create test data: Generate the necessary records and data to replicate the trigger scenario and cover different test cases.
    2. Execute the trigger event: Perform the specific DML operation that triggers the logic, such as insert, update, or delete.
    3. Assert the expected outcome: Check if the trigger behavior matches the expected results and validate the changes made by the trigger.
    4. Handle bulk testing: Ensure the trigger handles bulk data correctly by testing with multiple records in a single transaction.
    5. Handle governor limits: Verify that the trigger stays within the governor limits and handles large data volumes efficiently.

    By writing comprehensive unit tests, you can ensure the reliability and correctness of your trigger logic and avoid regressions when making changes to the code.

    29. What is a SOQL injection? How can you prevent it in Apex?

    Ans. SOQL injection is a security vulnerability that occurs when an application allows user-supplied input to directly manipulate a SOQL query. It can lead to unauthorized access, data breaches, or data corruption.

    To prevent SOQL injection in Apex, it is essential to use parameterized queries and sanitize user input. The recommended approach is to use bind variables in your SOQL queries, where the user input is passed as a parameter rather than concatenated directly into the query.

    Here’s an example of a vulnerable query without proper prevention:

    String input = 'example';
    String query = 'SELECT Id FROM Account WHERE Name = \'' + input + '\'';
    List<Account> accounts = Database.query(query);
    To prevent SOQL injection, you should use bind variables:
    String input = 'example';
    List<Account> accounts = [SELECT Id FROM Account WHERE Name = :input];

    By using bind variables, the input is automatically sanitized and treated as a parameter, reducing the risk of injection attacks.

    30. How can you implement a batchable interface in Apex? When would you use batch Apex?

    Ans. The Batchable interface in Apex allows you to process large sets of data by dividing the workload into smaller batches. It provides a way to handle complex or time-consuming operations that exceed the normal governor limits.

    To implement the Batchable interface, you need to define three methods:

    1. start: Collects the initial set of records to be processed and sets up the batch job.
    2. execute: Processes a batch of records and performs the required operations.
    3. finish: Handles any post-processing tasks after all batches have been executed.

    Batchable jobs can be queued and run asynchronously, allowing for the efficient processing of large data volumes without hitting governor limits.

    Batch Apex is typically used for scenarios such as data transformation, data migration, data cleansing, and complex calculations where large volumes of data need to be processed in a controlled and efficient manner.

    31. What is the purpose of a queueable interface in Apex? How does it differ from batch Apex?

    Ans. The Queueable interface in Apex provides a way to execute code asynchronously in the background. It allows you to chain and schedule the execution of jobs, providing flexibility and control over the order of execution.

    Unlike batch Apex, queueable jobs don’t have specific batch size limitations and can be used for smaller-scale processing. They are useful for scenarios where you need to perform lightweight asynchronous processing, integrate with external systems, or handle time-consuming tasks without blocking the user interface.

    To implement the Queueable interface, you define a class that implements the interface and implement the execute method. The execute method contains the logic to be executed asynchronously.

    Queueable Apex jobs can be enqueued and scheduled to run at a specific time or after the completion of other jobs, allowing for efficient job management and resource utilization.

    32. How can you handle exceptions and errors in Apex? What are the best practices?

    Ans. Exception handling in Apex allows you to handle and recover from runtime errors, ensuring the stability and reliability of your code. When an exception occurs, the normal flow of execution is disrupted, and control is transferred to the exception handling code.

    In Apex, you can handle exceptions using try-catch blocks. The try block contains the code that may throw an exception, and the catch block handles the exception and defines the desired behavior.

    Here’s an example of exception handling in Apex:

    try { 
         // Code that may throw an exception Integer result = 10 / 0; 
         // Division by zero 
        } 
    catch (Exception e) { 
        // Exception handling code System.debug('An exception occurred: ' + e.getMessage()); 
    }

    In the example, if an exception occurs during the division operation, the control is transferred to the catch block, and the exception message is logged.

    Best practices for exception handling in Apex include:

    1. Catch specific exceptions: Handle specific exceptions rather than using a general catch-all block to handle different types of exceptions differently.
    2. Provide meaningful error messages: Log or display informative error messages to help with troubleshooting and debugging.
    3. Graceful error handling: Handle exceptions gracefully and provide fallback or alternative paths of execution when errors occur.
    4. Use system exceptions when appropriate: Utilize standard system exceptions for common error conditions, such as DmlException or QueryException.

    By implementing effective exception handling, you can improve the robustness and reliability of your Apex code.

    33. Explain the concept of a “helper” class in Apex. Why would you use it?

    Ans. In Apex, a “helper” class refers to a class that provides reusable methods or functionality to assist other classes or components. Helper classes are used to modularize code, improve code organization, and promote reusability.

    Here are some reasons why you would use a helper class:

    1. Code organization: Helper classes separate specific functionality from the main class, making the codebase more manageable and maintainable.
    2. Reusability: Helper methods can be shared and used by multiple classes or components, avoiding code duplication.
    3. Encapsulation: By encapsulating related functionality in a helper class, you can provide a clean and concise API to other classes, abstracting the underlying implementation details.
    4. Testability: Helper methods can be unit tested independently, simplifying the testing process and ensuring the correctness of the functionality.
    5. Modularity: Helper classes can be easily updated or replaced without affecting the main class, promoting code extensibility and flexibility.

    Overall, using helper classes helps improve code structure, maintainability, and code reuse in Apex development.

    34. How can you make a callout to an external system from Apex code?

    Ans. To make a callout to an external system from Apex code, you can use Apex HTTP classes. Salesforce provides a robust set of classes for making HTTP requests and handling responses.

    Here’s an example of making a callout using Apex HTTP classes:

    HttpRequest request = new HttpRequest(); 
    request.setEndpoint('https://api.example.com/endpoint'); 
    request.setMethod('GET'); 
    HttpResponse response = new HttpResponse(); 
    Http http = new Http(); try { response = http.send(request); 
    if (response.getStatusCode() == 200) { 
         // Handle successful response String responseBody = response.getBody(); 
         // Process the response 
         } 
         else { 
         // Handle error response String errorMessage = 'Callout error: ' + response.getStatusCode() + ' - ' + response.getStatus(); // Handle the error 
         } 
    } 
    catch (Exception e) { 
    // Handle exception System.debug('Exception: ' + e.getMessage()); 
    }

    In the example, an HTTP GET request is made to an external API endpoint. The response is then handled based on the status code and processed accordingly.

    Apex HTTP classes allow you to make various types of HTTP requests, set request headers, handle request and response bodies, and handle errors or exceptions that may occur during the callout.

    35. What is the purpose of a future method in Apex? When would you use it?

    Ans. The “future” method in Apex is used to perform long-running or time-consuming operations asynchronously. It allows you to execute a method in the background without blocking the user interface.

    A future method is defined using the @future annotation and must return void. It can be called trigger handlers, Visualforce pages, or other Apex code.

    Here’s an example of a future method:

    public class MyFutureClass { 
         @future public static void performLongOperation() 
         { 
              // Perform long operation asynchronously // ... 
         } 
    }

    In the example, the performLongOperation the method is marked with the @future annotation, indicating that it should be executed asynchronously.

    Future methods are commonly used for tasks such as sending emails, making external callouts, performing calculations, or executing any other operations that may take a significant amount of time.

    By using future methods, you can offload time-consuming operations to run asynchronously and ensure a smooth user experience.

  • All You Need to Know About Salesforce Governor Limits

    All You Need to Know About Salesforce Governor Limits

    The concept of Salesforce Governor Limits exists because Salesforce and Apex run in a multi-tenant environment.

    In this article, I will explain what Governor Limits actually are in Salesforce. I’ll also provide some examples of the different types while highlighting why they are so important within a multi-tenancy set-up.

    Salesforce Multi-tenancy => Salesforce architecture is so popular because of its multi-tenancy. 

    Multitenancy is a means of providing a single application to multiple organizations, such as different companies or departments within a company, from a single hardware-software stack. Because of multitenancy, any developer can develop an application, upload it to the cloud, and easily share it with multiple clients or groups. Multiple users share the same server and applications, making it very cost-effective. In Salesforce, thanks to this multi-tenant architecture, all customer data is stored in a single database.

    Salesforce Governor Limits?

    In order for the code to run efficiently, Salesforce.com sets certain restrictions. Simply put, Salesforce Governor Limits are usage limits enforced by Salesforce to ensure efficient processing. They enable multiple users of the platform without limiting performance.

    Types of Salesforce Governor Limits

    • Per-transaction Certified Managed Package Apex Limits
    • Static Apex Limits
    • Lightning Platform Apex Limits
    • Size-specific Apex Limits
    • Per-transaction Apex Limits
    • Miscellaneous Apex Limit

    dont miss out iconDon’t forget to check out: Learn About the Governor Limits in Salesforce

    Per Transaction Certified Managed Package Limits: If a managed package developed by a Salesforce ISV has passed a security review, it is generally granted higher transaction limits.

    Overview Governor Limit
    SOQL queries issued (total number) 1100
    Records retrieved by Database.getQueryLocator (total number) 110000
    SOSL queries issued (total number) 220
    DML statements issued (total number) 1650
    Governor Limits in Salesforce for the total number of callouts (HTTP requests or web services calls) per transaction 1100
    SendEmail methods allowed (total number) 110

    Static Apex Limit: Apex Limits that apply to all transactions.

    Overview Governor Limit
    Default timeout of callouts (HTTP requests or Web services calls) in a transaction 10 sec.
    Max. size of callout request or response (HTTP request or Web services call) 6 MB for synchronous Apex | 12 MB for asynchronous Apex
    Max. SOQL query run time prior to transaction cancellation by Salesforce 120 sec.
    Max. number of class and trigger code units in Apex deployment 5000
    Batch size of Apex trigger 200
    Batch size for loop list 200
    Max. record number returned for a Batch Apex query in Database.QueryLocator 50000000

    Per-Transaction Apex Limits: These limits are calculated for each Apex transaction. For Batch Apex, these limits are reset for each execution of a batch of records in the execution method.

    Overview Governor Limits for Synchronous Transactions Governor Limits for Asynchronous Transactions
    SOQL queries issues(total numbers) 100 200

    Record retrieved by SOQL queries

    (total numbers)

    5000

    Record retrieved by Database.getQueryLocator (total

    number)

    10000
    SOSL queries issued (total number) 20
    Records retrieved by one SOSL query (total number) 2000
    DML statements issued (total number) 150
    Records processed as a result of DML statements, Approval.process, or database.emptyRecycleBin (total number) 10000
    Stack depth total for any Apex invocation that recursively fires triggers because of insert, update, or delete statements 16
    Callouts (HTTP requests or web services calls) per transaction  (total number) 100
    Max. cumulative timeout for all callouts (HTTP requests or Web services calls) per transaction 120 sec.
    Max. number of methods with the future annotation allowed per Apex invocation 50 0 in batch and future contexts; 1 in queueable context
    Max. number of Apex jobs added to the queue with System.enqueueJob 50 1
    Allowed sendEmail methods (total number) 10
    Heap size total 6MB 12MB
    Max. CPU time on the Salesforce servers 10 thousand milliseconds. 60 thousand milliseconds.
    Max. execution time per Apex transaction 10 min.
    Max. number of push notification method calls allowed per Apex transaction 10
    Max. number of push notifications that can be sent in each push notification method call 2000

    Lightning Platform Apex Limit: These limits are not specific to the Apex transaction and are enforced by the Lightning platform.

    Overview Governor Limit
    The maximum number of asynchronous Apex method executions (Batch Apex, future methods, Queueable Apex, and Scheduled Apex) per 24-hour period Either 250,000 or the number of user licenses in the org multiplied by 200, whichever is greater
    The number of synchronous concurrent transactions for long-running transactions, which last longer than 5 seconds for each org. 10
    The maximum number of Apex classes scheduled concurrently 100. In Developer Edition org, the limit is 5
    The maximum number of Batch Apex jobs in the Apex flex queue that is in the Holding status 100
    The maximum number of Batch Apex jobs queued or active concurrently 5
    The maximum number of Batch Apex job start method concurrent executions 1
    The maximum number of batch jobs that can be submitted in a running test 5
    The maximum number of test classes that can be queued in a 24-hour period (in Production org other than Developer Edition) Either 500 or 10 multiplied by the number of test classes in the org, whichever is greater
    The maximum number of test classes that can be queued in a 24-hour period (Sandbox and Developer Edition org) Either 500 or 20 multiplied by the number of test classes in the org, whichever is greater
    The maximum number of query cursors open concurrently per user 50
    The maximum number of query cursors open concurrently per user for the Batch Apex start method 15
    The maximum number of query cursors open concurrently per user for Batch Apex execute and finish methods 5

    Size-Specific Apex Limit: Apex Limits related to code size.

    dont miss out iconCheck out another amazing blog here: Bypass Salesforce Governor Limits when Working with Files

    Overview Governor Limit
    The maximum number of characters in a class 1 million
    The maximum number of characters in a trigger 1 million
    The maximum amount of code used by all Apex codes in org1 6 MB
    The method size limit 2 65,535 bytecode instructions in a compiled form

    Miscellaneous Apex Limit: Inbound Email Limits, Push Notification Limits, Governor Limits for Salesforce API Requests, Chatter REST API Limits, SOAP API Call Limits, API Query Cursor Limits, Metadata Limits, SOQL and SOSL Governor Limits in Salesforce, Visualforce Limits

    Advantages of Governor Limits in Salesforce

    • Governor limits in Salesforce prevent other organizations from using and thus running lengthy code that can take up a lot of memory and even the entire cloud CPU.
    • Apex has completely different or unique coding limits.
    • These governor limits help us stay in the right coding space with Apex.

    Best Practices to Avoid Governor Limits 

    • Do not have DML statements or SOQL queries inside a For loop.
    • Try not to use DML or SOQL operations in a loop.
    • Try to bulkify the code and use Helper Methods.
    • Query large datasets.
    • If we want to process 50,000 records, use Batch Apex.
    • One trigger per object.
    • Use query and collection simplifications for loops.
    • Use @future Appropriately.
    • Avoid hard-coding IDs.

    I hope you now understand how governor limits in Apex work and how to avoid them.

    Conclusion

    We hope you now understand how governor limits work in Apex and how to avoid them. When working on code and managing an organization, it’s crucial to be aware of the limitations that Salesforce has.

  • What is Queueable Apex in Salesforce?

    What is Queueable Apex in Salesforce?

    This Apex allows you to submit jobs for asynchronous processing similar to future methods. We have to implement the Queueable interface to make the class queueable. Implementation of classes and methods must be declared as public or global. We can add the job to the queue and monitor them by the going to apex job from the quick find box or from the job id by adding this interface. The interface enables you to add jobs to the queue and you can monitor them. This is an enhanced way of running your asynchronous Apex code compared to using future methods. 

    The interface has only one method execute which takes one parameter of Queueable Context:

    public void execute(QueueableContext context) 
    { 
        // Your code here 
    }

    The important benefit of  Queueable interface methods is that some governor limits are higher than for synchronous Apex, such as heap size limits. 

    dont miss out iconDon’t forget to check out: Queueable Apex vs Batch Apex | Salesforce Developer Guide

    Queueable jobs are as similar to the future methods in that they’re both queued for execution, but they provide you with these additional benefits like:

    • This class can contain member variables of non-primitive data types, such as custom Apex types. All of those objects can be accessed when the job executes. 
    • One can chain one job to another job by starting a second job from a running job. These jobs are useful if your process depends on another process to have run first. 

     If the Apex transaction rolls back, any queueable jobs queued for execution by the transaction aren’t processed. 

    An example is the implementation of the Queueable interface. The execute method in this example inserts a new account:

    public class AsyncExecutionExample implements Queueable 
    { 
        public void execute(QueueableContext context) 
        { 
            Account a = new Account(Name='Acme',Phone='(415) 555-1212'); 
            insert a;         
        } 
    }

    dont miss out iconCheck out another amazing blog by Saurabh here: Learn All About the Batch Apex in 2023

    Call this method to add Job Id:

    ID jobID = System.enqueueJob(new AsyncExecutionExample());

    The job is added to the queue and will be processed when system resources become available. You can monitor the status of your job programmatically by querying AsyncApexJob or through the user interface in Setup by entering Apex Jobs in the Quick Find box, and selecting Apex Jobs. 

    Perform a SOQL query on AsyncApexJob by filtering on the job ID that the System.enqueueJob method returns to query information about your submitted job. 

  • All you Need to Know About Salesforce Apex Scheduler | The Ultimate Guide

    All you Need to Know About Salesforce Apex Scheduler | The Ultimate Guide

    Apex Scheduler

    Apex code that is scheduled to run at a specific time over a set period of time. A class that repeats at regular intervals is called a schedule apex in Salesforce. We need to implement the interface Schedulable in order to schedule an apex class. When you have to redeploy or alter this code, you can utilise it to schedule it to execute on the first of each month or on a certain day. Apex’s scheduler operates in system mode, allowing users to execute classes whether or not they are authorised to do so. Starting a career as a Salesforce Developer is incredibly intriguing because you can browse a new planned apex job every ten minutes. Using the appropriate code and technique, you can also access the scheduled batch apex from the developer console. 

    When utilising the Schedule Apex tab in the Salesforce user interface or the System.schedule method, you must first implement the Schedulable interface for the class in order to launch Apex classes to execute at a certain time 

    Implementing the Schedulable Interface

    Write an Apex class that implements the Schedulable interface supplied by Salesforce first if you want to schedule an Apex class to run periodically. 

    Whether or not the user has the authorization to execute a class, the scheduler runs as a system and all classes are executed. 

    Enter Scheduled Jobs in the Quick Find box in Setup, then choose Scheduled Jobs to monitor or halt the execution of a scheduled Apex job using the Salesforce user interface.  

    The Schedulable interface contains one method that must be implemented, and execute. 

    global void execute(SchedulableContext sc){} 

    The implemented method must be declared as global or public. 

    Use this method to instantiate the class you want to schedule. 

    dont miss out iconDon’t forget to check out: Apex Triggers in Salesforce | Here’s the Ultimate Salesforce Guide

    The following example implements the Schedulable interface for a class called mergeNumbers: 

    global class scheduledMerge implements Schedulable { 
        global void execute(SchedulableContext SC) { 
            mergeNumbers M = new mergeNumbers();  
        } 
    }

    To implement the class, execute this example in the Developer Console. 

    scheduledMerge m = new scheduledMerge(); 
    String sch = '20 30 8 10 2 ?'; 
    String jobID = system.schedule('Merge Job', sch, m);

    You can also use the Schedulable interface with batch Apex classes. The following example implements the Schedulable interface for a batch Apex class called batchable: 

    global class scheduledBatchable implements Schedulable { 
        global void execute(SchedulableContext sc) { 
            batchable b = new catchable();  
            database.executebatch(b); 
         } 
    }

    An easier way to schedule a batch job is to call the System.scheduleBatch method without having to implement the Schedulable interface. 

    Use the SchedulableContext object to keep track of the scheduled job when it’s scheduled. The SchedulableContext getTriggerID method returns the ID of the CronTrigger object associated with this scheduled job as a string. You can query CronTrigger to track the progress of the scheduled job. 

    To stop the execution of a job that was scheduled, use the System.abortJob method with the ID returned by the getTriggerID method. 

    Apex Scheduler Limits

    • There is a cap of 100 planned Apex jobs per user. By visiting the Scheduled Jobs page in Salesforce and generating a custom view with a type filter similar to “Scheduled Apex,” you can determine your current count. To obtain the number of Apex scheduled jobs, you can also programmatically query the CronTrigger and CronJobDetail classes.  
    • The most scheduled Apex executions per day are 250,000 or 200 times the number of user licences in your business, whichever is higher. All asynchronous Apex, including Batch Apex, Queueable Apex, Scheduled Apex, and Future Methods, are subject to this limit, which applies to your entire organisation. Make a request to the REST API limits resource to find out how many available asynchronous Apex executions there are. The REST API Developer Guide contains a section on List Organization Limits. Full Salesforce and Salesforce Platform user licences, App Subscription user licences, Chatter Only users, Identity users, and Company Communities users are among the licencing types that count against this cap. 

    dont miss out iconCheck out an amazing Salesforce video tutorial here: Introduction To Salesforce Apex | DataType | Collection | Conditional Statements

    Apex Scheduler Notes and Best Practices

    • Salesforce arranges for the class to run at the designated time. Depending on the availability of the service, actual execution may be postponed. 
    • If you intend to book a class from a trigger, exercise extreme caution. The trigger can’t add more scheduled classes than the limit, therefore you must be able to assure that.
    •  Take into account API bulk updates, import wizards, user interface mass record changes, and any other situations where multiple records can be modified simultaneously. 
    • Although more processing can be done in the execute method, we advise that all processing be done in a different class.
    • Scheduled Apex does not handle synchronous Web service callouts. Make asynchronous callouts by implementing Queueable Apex in your code. interface for the AllowsCallouts marker. if the batch job being run by your scheduled Apex uses the database. Callouts are supported by the batch class via the AllowsCallouts marker interface. Read about using Batch Apex. 
    • When a Salesforce service is offline for maintenance, any Apex jobs that were scheduled to run during that period will now run when system resources become available after the service has resumed. When the service resumes, all scheduled Apex jobs that were already in progress are rolled back and scheduled again. Due to surges in system utilisation following significant service upgrades, planned Apex jobs may start with a longer delay than usual. 
    • From initialization through successive scheduled runs, scheduled job objects, along with the member variables and properties, remain unchanged. In subsequent job executions, the object state from the moment System.schedule() was called is preserved. 
    • Using Database.stateful in Batch Apex, it is feasible to force a new serialised state for fresh jobs. Use the temporary keyword with Scheduled Apex to prevent member variables and properties from being persistent. Read about using the transitory keyword. 

     

  • Optimization of Salesforce Org – Everything You Need to Know

    Optimization of Salesforce Org – Everything You Need to Know

    In this blog we’ll learn about Optimization, why is it necessary, how can we optimize apex class, the highest execution duration of an apex class, the highest execution duration of an SOQL and finally the highest execution duration of a Synchronous and Asynchronous transactions.  

    So, let’s get going. 

    Optimization

    It is the process of enhancing system capabilities through various methods. For example: Reducing the space/ time complexity of a code. 

    Why It Is Done?

    • To increase the overall efficiency of the system. 
    • To improve the reliability, consistency, and accuracy of the system. 
    • To save time. 
    • For better resource utilization. 
    • To provide seamless experience to the user. 
    • To improve the overall performance of the system in order to meet business requirements. 

    dont miss out iconDon’t forget to check out: Queueable Apex vs Batch Apex | Salesforce Developer Guide

    How Can we Optimize Apex Class?

    Optimization can be done by following some points below:  

    1. Don’t write DML and SOQL inside loops because if we run a code that will execute the query for over 100-150 times then governor limits would increase and we will get error of too many SOQL/ DML statements. To optimize the code, one should not use them within a loop.  
    2. By running fewer queries, SOQL performance can be increased and system can be optimised. 
    3. Ensure that the queries are selective. 
      • A query is said to be selective if one of the query filters is on an indexed field. But what does the query filter do?  
      • This filter reduces the resulting number of rows below a system-defined threshold. For example: When you apply a filter such as “select name from contacts where id=10”. Hence, the SOQL query performance improves. 
      • It can also improve further if you use two or more filters. 
    4. Performance of an apex code can be increased by using the platform cache feature of the Salesforce Lightning platform. We can use this feature to reduce the server response time and use platform cache. But how can we enable this? 
      • By default, Developer org has cache capacity of 0 MB. We can request a trial cache of 10 MB. 
      • To request a trial, go to Setup in Developer org.  
      • In the Quick Find box, enter cache and then click Platform Cache 
      • Click Request Trial Capacity and wait for the email notification of Platform Cache trial to be active. Salesforce approves trial requests immediately but it can take a few minutes to receive the mail.

    5. Use of the limit apex methods can be done in order to avoid reaching the governor limits. Limits methods return the specific limit for a particular governor. For example: getLimitHeapSize() method returns the  total amount of memory (in bytes) which can be used for the heap. 

    6. By using maps, we can avoid the nested for and do-while loops. 

    dont miss out iconCheck out another amazing blog by Tanya here: Multi-Factor Authentication in Salesforce – The Brief Guide

    What must be the maximum execution duration of an apex class?

    • Maximum execution time for each Apex transaction is 10 minutes. 

    What must be the maximum execution duration of an SOQL?

    • Maximum SOQL query runtime before the transaction can be cancelled by Salesforce is 120 seconds.

    Highest execution duration of a Synchronous and Asynchronous transactions?

    • For synchronous transactions, Salesforce limits the CPU usage to 10 seconds and for an asynchronous transaction it must be 60 seconds.

     

  • Queueable Apex vs Batch Apex | Salesforce Developer Guide

    Queueable Apex vs Batch Apex | Salesforce Developer Guide

    Queueable Apex

    Apex processes that run for a long time, such as extensive database operations or external web service callouts, can be run asynchronously by implementing the Queueable interface and adding a job to the Apex job queue.

    Queueable jobs:

    • Getting an ID for the job
    • Using non-primitive types
    • Can do 50 chaining jobs (one queue can call to another queue)

    Queueable Syntax

    public class TestDemoQueueable implements Queueable {
        public void execute(QueueableContext qCntxt) {
            Account a = new Account(Name='Acme',Phone='(415) 555-1212');
            insert a;        
        }
    }

    To add this class as a job on the queue, call this method:

    ID jobID = [Method] System.enqueueJob(new TestDemoQueueable()); //Instantiate

    [Method] can be called from the anonymous window and other classes & Triggers.

    Governor limit is 10k record DML updates in one transaction.

    AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];

    Chaining:

    public class FirstQueueableclsExample implements Queueable{
        public void (QueueableContext context){
            //further processing.
            System.enqueueJob(new SecondJob()); //chaining of Jobs.
        }
    }

    Example: Create Contact with Name for Account created

    dont miss out iconDon’t forget to check out: Callouts from Batch Apex and Calling One Batch Apex to Another Batch | Salesforce Tutorial Guide

    Queueable Class

    public class ContactCreationQueueable implements Queueable{
        private List<Account> accListToCreateContacts;
        public ContactCreationQueueable(List<Account> expectingAccountFromTrigger){
            this.accListToCreateContacts=expectingAccountFromTrigger;        
        }
        public void execute(QueueableContext qCntxt){
            List<Contact> contactToUpdate =new List<Contact>();        
            //Loop on all accounts that are inserted.
            for(Account acc:accListToCreateContacts){
                Contact con= new Contact();
                con.LastName=acc.Name;
                con.AccountId=acc.Id;
                contactToUpdate.add(con); //Add each Contact to List
            }
            if(contactToUpdate.size()>0){
                Insert contactToUpdate;            
            }        
        }    
    }

    Trigger

    trigger AccountTriggerQueue on Account (after insert) {
        if(Trigger.isAfter && Trigger.isInsert){
            system.enqueueJob(new ContactCreationQueueable(Trigger.new)); //Chaining        
        }
    }

    Limitation

    • Queueable can’t handle millions of records in one job.
    • Only one job can be scheduled at a time.
    • In the developer edition stack depth for chaining the jobs is limited to 5 including the parent job.

    Batch Apex

    • Batch apex is used to run large jobs (like millions) that would exceed normal processing units.
    • Using Batch apex, we can process records asynchronously in batches.
    • Batch apex processes up to 50million records in the background, unlike Future and Queueable.

    Batch Apex Syntax

    public class MyClass implements Database.Batchabale{
        Start(){
            //Query all the records to process.
        }
        Execute(){
            //Process batch of records from the start.
            Finish(){
                //Any post processing logic Eg:send Mail
            }
        }
    }

    Batch apex methods:

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

    How Batch Apex Works

    Start(): query all records :lets say 100000 [Sends 2000 records every time(Maximum BatchSize)]

    Execute(): going to process 20000 records only

    Finish(): Post-Processing and another task like sending mail or handling exception.

    Batch Size

    • Minimum batch size -1
    • Maximum batch size -2000
    • Default will be -200

    Way of Calling:

    Database.executeBatch=(new MyClass(),2000);
    ExampleBatchClass myBatchObject = new ExampleBatchClass();
    Id batchId = Database.executeBatch(myBatchOBject);

    Example:

    public class TestDemoBatch 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> subListFromStartMethod){
            for(Account acc:subListFromStartMethod){
                acc.Name='Demo Batch-'+acc.Name;
            }
            UPDATE subListFromStartMethod;
        }
        public void finish(Database.BatchableContext bc){
            System.debug('@@Post Processing Done');
            Database.execute(new BatchClass2()); //Chaining of Batch Jobs
        }
    }

    dont miss out iconCheck out an amazing Salesforce video tutorial here: Apex Scheduler in Salesforce | Asynchronous Apex

    Batch Apex over Queueable

    • It allows the processing 50million of records in the background
    • Best suitable for long-running processes

    Limitation

    • Can have only 5 batch jobs running at a time.
    • Execution may be delayed due to server availability.
    • @Future methods are not allowed.
    • Future methods cannot be called from Batch Apex.

    Using Queueable Over Batch Apex:

    • A future method runs in the background, asynchronously. We can call a future method for executing long-running operations, such as callouts to external web services or other operations, on its own time as we can’t call future methods from the batch class.
    • It comes in handy when we need to have both the operations of Batch and Future method and it should implement Queueable Interface.
    • Queueable apex can be called from the Future and Batch class.
    • Moreover Queueable apex supports getContent/getContentAsPDF() method.
    • In Queueable apex, we can chain up to 50 jobs and in developer edition, we can chain up to 5 jobs only whereas in BatchApex 5 concurrent jobs are allowed to run at a time.
  • Salesforce REST API | HTTP and Callout Basics | All You Need to Know

    Salesforce REST API | HTTP and Callout Basics | All You Need to Know

    HTTP and Callout Basics

    REST callouts depend on HTTP. To see how callouts work, it’s useful to comprehend a couple of things about HTTP. Each callout demand is related to an HTTP technique and an endpoint. The HTTP technique shows what sort of activity is wanted. 

    Zenith callouts to an outer help.

    The least difficult solicitation is a GET demand (GET is an HTTP technique). A GET demand implies that the sender needs to get data about an asset from the worker. At the point when the worker gets and measures this solicitation, it restores the solicitation data to the beneficiary. A GET demand is like exploring a location in the program. At the point when you visit a site page, the program plays out a GET demand in the background. In the program, the consequence of the route is another HTML page that is shown. With a callout, the outcome is the reaction object. 

    To outline how a GET demand functions, open your program and explore the accompanying URI: https://th-summit http-callout.herokuapp.com/creatures. Your program shows a rundown of creatures in an unusual organization in light of the fact that the assistance restores the reaction in a configuration called JSON. Once in a while, a GET reaction is likewise designed in XML

    Coming up next are portrayals of regular HTTP techniques.

    On the off chance that you have some spare time, peruse the thorough rundown of all HTTP techniques in the Resources segment

    Notwithstanding the HTTP technique, each solicitation sets a URI, which is the endpoint address at which the assistance is found. For instance, an endpoint can be an interface/asset. In the model in the “HTTP and Callout Basics” unit, the endpoint is https://th-summit http-callout.herokuapp.com/creatures. 

    At the point when the worker measures the solicitation, it sends a status code in the reaction. The status code demonstrates whether the solicitation was handled effectively or whether mistakes were experienced. On the off chance that the solicitation is effective, the worker sends a status code of 200. You’ve likely seen some other status codes, like 404 for a document not found or 500 for an inside worker mistake. 

    On the off chance that you actually have leisure time subsequent to perusing the rundown of HTTP strategies, look at the rundown of all reaction status codes in the Resources area. In case you’re struggling dozing around evening time, these two assets can help.

    Get Data from a Service

    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
    request.setMethod('GET');
    HttpResponse response = http.send(request);
    // If the request is successful, parse the JSON response.
    if (response.getStatusCode() == 200) {
        // Deserialize the JSON string into collections of primitive data types.
        Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
        // Cast the values in the 'animals' key as a list
        List<Object> animals = (List<Object>) results.get('animals');
        System.debug('Received the following animals:');
        for (Object animal: animals) {
            System.debug(animal);
        }
    }

    dont miss out iconDon’t forget to check out: Low-Code Salesforce REST API Integration – All You Need to Know

    Send Data to a Service

    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
    request.setMethod('POST');
    request.setHeader('Content-Type', 'application/json;charset=UTF-8');
    // Set the body as a JSON object
    request.setBody('{"name":"mighty moose"}');
    HttpResponse response = http.send(request);
    // Parse the JSON response
    if (response.getStatusCode() != 201) {
        System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
    } else {
        System.debug(response.getBody());
    }

    Test Callouts

    public class AnimalsCallouts {
        public static HttpResponse makeGetCallout() {
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
            request.setMethod('GET');
            HttpResponse response = http.send(request);
            // If the request is successful, parse the JSON response.
            if (response.getStatusCode() == 200) {
                // Deserializes the JSON string into collections of primitive data types.
                Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                // Cast the values in the 'animals' key as a list
                List<Object> animals = (List<Object>) results.get('animals');
                System.debug('Received the following animals:');
                for (Object animal: animals) {
                    System.debug(animal);
                }
            }
            return response;
        }
        public static HttpResponse makePostCallout() {
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
            request.setMethod('POST');
            request.setHeader('Content-Type', 'application/json;charset=UTF-8');
            request.setBody('{"name":"mighty moose"}');
            HttpResponse response = http.send(request);
            // Parse the JSON response
            if (response.getStatusCode() != 201) {
                System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
            } else {
                System.debug(response.getBody());
            }
            return response;
        }        
    }

    Test a Callout with StaticResourceCalloutMock

    To test your callouts, utilize mock callouts by either executing an interface or utilizing static assets. In this model, we utilize static assets and a false interface later on. The static asset contains the reaction body to return. Once more, when utilizing a counterfeit callout, the solicitation isn’t shipped off the endpoint. All things being equal, the Apex runtime knows to look into the reaction indicated in the static asset and return it all things considered. The Test.setMock strategy educates the runtime that mock callouts are utilized in the test technique. How about we see mock callouts in real life. In the first place, we make a static asset containing a JSON-designed string to use for the GET demand.

    In the Developer Console, select File | New | Static Resource. For the name, enter GetAnimalResource. For the MIME type, select text/plain, even though we are using JSON. Click Submit. In the tab that opens for the resource, insert the following content. Make sure that it is all on one line and doesn’t break to the next line. This content is what the mock callout returns. It’s an array of three woodland creatures.

    {“animals”: [“pesky porcupine”, “hungry hippo”, “squeaky squirrel”]}

    You’ve successfully created your static resource! Now, let’s add a test for our callout that uses this resource. In the Developer Console, select File | New | Apex Class. For the class name, enter AnimalsCalloutsTest and then click OK. Replace the autogenerated code with the following test class definition.

    @isTest
    private class AnimalsCalloutsTest {
        @isTest static  void testGetCallout() {
            // Create the mock response based on a static resource
            StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
            mock.setStaticResource('GetAnimalResource');
            mock.setStatusCode(200);
            mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
            // Associate the callout with a mock response
            Test.setMock(HttpCalloutMock.class, mock);
            // Call method to test
            HttpResponse result = AnimalsCallouts.makeGetCallout();
            // Verify mock response is not null
            System.assertNotEquals(null,result,
                'The callout returned a null response.');
            // Verify status code
            System.assertEquals(200,result.getStatusCode(),
                'The status code is not 200.');
            // Verify content type   
            System.assertEquals('application/json;charset=UTF-8',
                result.getHeader('Content-Type'),
                'The content type value is not expected.');  
            // Verify the array contains 3 items     
            Map<String, Object> results = (Map<String, Object>) 
                JSON.deserializeUntyped(result.getBody());
            List<Object> animals = (List<Object>) results.get('animals');
            System.assertEquals(3, animals.size(),
                'The array should only contain 3 items.'          
            );
        }
    }

    Press CTRL+S to save.

    Select Test | Always Run Asynchronously. If you don’t select Always Run Asynchronously, test runs that include only one class run synchronously. You can open logs from the Tests tab only for synchronous test runs.

    To run the test, select Test | New Run.

    From the Test Classes list, select AnimalsCalloutsTest.

    Click Add Selected | Run.

    dont miss out iconCheck out another amazing blog by Sumit Kumar here: What is Queueable Apex in Salesforce – All You Need to Know
    67
    The test result is displayed in the Tests tab under a test run ID. When the test execution finishes, expand the test run to view details. Now double-click AnimalCallouts in the Overall Code Coverage pane to see which lines are covered by your tests.

    Find out about utilizing callouts in triggers and in nonconcurrent Apex, and about making offbeat callouts. 

    When making a callout from a strategy, the technique trusts that the outside assistance will send back the callout reaction prior to executing ensuing lines of code. Then again, you can put the callout code in a nonconcurrent strategy that is clarified with @future(callout=true) or utilize Queueable Apex. Thusly, the callout runs on a different string, and the execution of the calling strategy isn’t hindered. 

    When making a callout from a trigger, the callout should not obstruct the trigger interaction while hanging tight for the reaction. For the trigger to have the option to make a callout, the strategy containing the callout code should be explained with @future(callout=true) to run in a different string.

  • What is Queueable Apex in Salesforce  – All You Need to Know

    What is Queueable Apex in Salesforce – All You Need to Know

    Delivered in Winter ’15, Queueable Peak is basically a superset of future strategies with some extra #awesomesauce. We took the effortlessness of future strategies and the force of Group Summit and combined them as one to shape Queueable Zenith! It gives you a class structure that the stage serializes for you, a disentangled interface without start and finish techniques, and even permits you to use something beyond crude contentions! It is called by a straightforward System.enqueueJob() strategy, which restores a task ID that you can screen. It thrashes cut bread hands! 

    Queueable Pinnacle permits you to submit occupations for nonconcurrent handling like future techniques with the accompanying extra advantages: 

    Non-crude sorts: Your Queueable class can contain part factors of non-crude information types, for example, sObjects or custom Zenith types. Those items can be gotten to when the work executes

    Observing: When you present your work by conjuring the System.enqueueJob strategy, the technique restores the ID of the AsyncApexJob record. You can utilize this ID to distinguish your work and screen its encouraging, either through the Salesforce UI in the Pinnacle Occupations page, or automatically by questioning your record from AsyncApexJob

    Binding positions: You can anchor one occupation to another work by beginning a second occupation from a running position. Anchoring occupations is valuable on the off chance that you need to do some consecutive preparation.

    dont miss out iconDon’t forget to check out: How To Use Database.Stateful Interface In Batch Apex In Salesforce

    Queueable Versus Future

    Since queueable techniques are practically identical to future strategies, more often than not you’ll presumably need to utilize queueable rather than future strategies. Nonetheless, this doesn’t really mean you should return and refactor all your future techniques at the present time. 

    Another motivation to utilize future strategies rather than queueable is the point at which your usefulness is some of the time executed simultaneously, and at times non concurrently. It’s a lot simpler to refactor a strategy as such than changing over to a queueable class. This is helpful when you find that piece of your current code should be moved to async execution. You can just make a comparative future strategy that wraps your coordinated technique like so:

    @future
    static void myFutureMethod(List<String> params) {
        // call synchronous method
        mySyncMethod(params);
    }

    Queueable Syntax

    public class SomeClass implements Queueable {
        public void execute(QueueableContext context) {
            // awesome code here
        }
    }

    Things to Remember

    Queueable Summit is an extraordinary new instrument yet there are a couple of things to keep an eye out for: 

    The execution of a lined occupation counts once as a detriment to as far as possible for offbeat Summit strategy executions

    You can amount to 50 positions to the line with System.enqueueJob in a solitary exchange. 

    dont miss out iconCheck out another amazing blog by Sumit here: Future Methods in Apex | The Salesforce Developer Guide

    When binding positions, you can add just one occupation from an executing position with System.enqueueJob, which implies that just a single kid occupation can exist for each parent queueable work. Beginning different kid occupations from a similar queueable occupation is a no-no. 

    No restriction is upheld on the profundity of tied positions, which implies that you can affix one occupation to another work and rehash this interaction with each new kid task to connect it to another youngster’s work. Notwithstanding, for Engineer Version and Preliminary organizations, the greatest stack profundity for fastened positions is 5, which implies that you can chain occupations multiple times and the most extreme number of occupations in the chain is 5, including the underlying guardian queueable work.

  • Using Batch Apex | Apex Developer Guide | Salesforce

    Using Batch Apex | Apex Developer Guide | Salesforce

    Cluster Apex is utilized to run huge positions (think thousands or millions of records!) that would surpass ordinary preparing limits. Utilizing Batch Apex, you can handle records non concurrently in clusters (thus the name, “Group Apex”) to remain inside stage limits. On the off chance that you have a ton of records to measure, for instance, information purifying or documenting, Batch Apex is presumably your best arrangement.

    Here are the means by which Batch Apex works in the engine. Suppose you need to deal with 1 million records utilizing Batch Apex. The execution rationale of the group class is called once for each clump of records you are preparing. Each time you summon a group class, the employment is put on the Apex work line and is executed as a discrete exchange. This usefulness has two magnificent focal points:

    Each exchange begins with another arrangement of lead representative cutoff points, making it simpler to guarantee that your code remains inside the lead representative execution limits.

    In the event that one clump neglects to measure effectively, all other fruitful bunch exchanges aren’t moved back.

    dont miss out iconDon’t forget to check out: Salesforce Apex Winter Release 21 – All You Need To Know

    Batch Apex Syntax

    To compose a Batch Apex class, your class must execute the Database. Batchable interface and incorporate the accompanying three strategies:

    Start

    Used to gather the records or has a problem with to be passed to the interface strategy execute for handling. 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 work.

    More often than not a QueryLocator does the stunt with a straightforward SOQL inquiry to create the extent of items in the group work. In any case, on the off chance that you have to accomplish something insane like circle through the aftereffects of an API call or pre-measure records prior to being passed to the execute strategy, you should look at the Custom Iterators connect in the Resources area.

    With the QueryLocator object, the lead representative breaking point for the absolute number of records recovered by SOQL questions is circumvented and you can inquiry up to 50 million records. Nonetheless, with an Iterable, the lead representative breaking point for the absolute number of records recovered by SOQL inquiries is as yet authorized.

    Execute

    Plays out the real preparing for each lump or “clump” of information passed to the strategy. The default cluster size is 200 records. Bunches of records are not ensured to execute in the request they are gotten from the beginning strategy.

    This technique takes the accompanying:

    A reference to the Database.BatchableContext object.

    A rundown of sObjects, for example, List<sObject>, or a rundown of defined kinds. On the off chance that you are utilizing a Database.QueryLocator, utilize the brought list back.

    The finish used to execute post-handling tasks (for instance, sending an email) and is called once after all bunches are prepared.

    This is what the skeleton of a Batch Apex class resembles:

    public class MyBatchClass implements Database.Batchable<sObject> {
        public (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {
            // collect the batches of records or objects to be passed to execute
        }
        public void execute(Database.BatchableContext bc, List<P> records){
            // process each batch of records
        }
        public void finish(Database.BatchableContext bc){
            // execute any post-processing operations
        }
    }

    dont miss out iconCheck out another amazing blog by Sumit here: Collections In Salesforce | Apex Developer Guide

    Best Practices

    Likewise, with future techniques, there are a couple of things you need to remember when utilizing Batch Apex. To guarantee quick execution of clump occupations, limit Web administration callout times and tune questions utilized in your cluster Apex code. The more extended the bunch work executes, the more probable other lined positions are postponed when numerous positions are in the line. Best practices include:

    Possibly use Batch Apex on the off chance that you have more than one bunch of records. In the event that you need more records to run more than one cluster, you are most likely good at utilizing Queueable Apex.

    Tune any SOQL inquiry to accumulate the records to execute as fast as could reasonably be expected.

    Limit the quantity of nonconcurrent demands made to limit the opportunity of postponements.

    Utilize extraordinary consideration in the event that you are intending to summon a clump work from a trigger. You should have the option to ensure that the trigger won’t add more bunch occupations than the breaking point.

  • Schedule Apex in Salesforce | Apex Developer Guide

    Schedule Apex in Salesforce | Apex Developer Guide

    Schedule Apex in Salesforce

    1. If you want to run apex classes at a specific time then we use schedule apex.
    2. If you want to schedule an apex class, then the apex class has to implement to the “Schedulable” Interface.
      • Syntax: Public class example implements Schedulable {}
    3. If any apex class which implements schedulable interface has to define the “execute” method
      • Syntax: Public void execute(schedulablecontext sc){}
    4. Operation or Logic which you want to schedule should be defined in the execute method.

    Symbols and Meanings:

    * Every (Everyday,EveryMonth, EveryHour,EveryMinute)

    L Last (Lastday, LastMonth, lastFriday)

    W Nearest working day

    ? Not Sure

    , 3,5,7 (every 3rd,5th ,7th)

    dont miss out iconDon’t forget to check out: Types of Collections in Apex Salesforce | Explained

    Example 1: Scheduling the apex at 1:53 PM on 7th Dec 2017, for deleting contacts which are created today

    Apex Class:

    public class Scheduleapex implements schedulable {
        public void execute(SchedulableContext sc){
            list<contact> accs=[select id,lastname from contact where createddate=TODAY];
            delete accs;
        }
    }
    // Code to schedule Apex Class 
    Scheduleapex sa=new Scheduleapex();
    string expression='0 53 13 7 12 ? 2017';
    system.schedule('vipin',expression,sa);
    

    Example2: Calling batch apex from schedule apex, and performing different DML operations.

    public class Scheduleapex implements schedulable {
        public void execute(SchedulableContext sc){
            list<contact> accs=[select id,lastname from contact where createddate=TODAY];
            delete accs;
            BatchEx3 be=new BatchEx3();
            database.executeBatch(be,5);
        }
    }
    Global class BatchEx3 implements Database.Batchable<Sobject>{
        Global Database.QueryLocator start(database.BatchableContext bc ){
            Return Database.getQueryLocator('Select id from account where createddate=Last_Month');
        }
        Global void Execute(Database.BatchableContext bc,List<account> acc){
            for(integer i=0;i<50;i++){
                account a=new account();
                a.name='Test';
                a.Email__c='Test@gmail.com';
                insert a;
            }
        }
        Global void Finish(Database.Batchablecontext bc){}
    }
    //Code to schedule
    Scheduleapex sa=new Scheduleapex();
    string expression='0 42 14 7 12 ? 2017';
    system.schedule('vipin1', expression,sa);
    

    Example3: Calling Batch apex, Queueable apex, future method from Schedule apex, and performing various DML operations. Apex Program:

    // Schedule Apex
    public class Scheduleapex implements schedulable {
        public void execute(SchedulableContext sc){
            list<contact> accs=[select id,lastname from contact where createddate=TODAY];
            delete accs;
            BatchEx3 be=new BatchEx3();//Calling batch apex
            database.executeBatch(be,5);
            ChainingApex2 ac=new ChainingApex2();//Calling Queueabe apex
            system.enqueueJob(ac);
            FutureAcc fa=new FutureAcc();//calling future method
            fa.accss();
        }
    }
    // Batch Apex
    Global class BatchEx3 implements Database.Batchable<Sobject>{
        Global Database.QueryLocator start(database.BatchableContext bc ){
            Return Database.getQueryLocator('Select id from account where createddate=Last_Month');
        }
        Global void Execute(Database.BatchableContext bc,List<account> acc){
            for(integer i=0;i<50;i++){
                account a=new account();
                a.name='test1;
                a.Email__c='Test@gmail.com';
                insert a;
            }
        }
        Global void Finish(Database.Batchablecontext bc){}
    }
    

    Queueable Apex:

    public class ChainingApex2 implements Queueable {
        public void execute(queueablecontext qc1){
            list<account> acc2=[select name,phone,industry,fax,sic from account where
            industry='banking'];
            for(account b:acc2){
                b.fax='143143143';
                id x=qc1.getJobId();
                b.Sic=x;
                update b;
            }
            ChainingApex1 ca=new ChainingApex1();
            id ids=system.enqueueJob(ca);
        }
    }
    public class chainingApex1 implements Queueable {
        public void execute(queueablecontext qc){
            list<account> acc1=[select name,phone,industry,fax,description from account where
            industry='banking'];
            for(account a:acc1){
                a.phone='9999999';
                id x1=qc.getJobId();
                a.description=x1;
                update a;
            }
        }
    }
    

    dont miss out iconCheck out another amazing blog by Kirandeep here: Controller Extensions in Salesforce | The Developer Guide

    Future Method:

    public class FutureAcc {
        public void acc(){
            List<Account> acc=[select id,Email__c,fax,phone from Account where industry='banking'];
            for(account a:acc){
                // a.phone='+9999999';
                a.Email__c='salman@gmail.com';
                update a;
            }
        }
        @future
        public static void accs(){
            List<Account> acc=[select id,Email__c,fax,phone from Account where industry='Education'];
            for(account a:acc){
                //a.fax='+911111111';
                a.Email__c='Test@gmail.com';
                update a;
            }
        }
        public void accss(){
            acc();
            accs();
        }
    }
    
  • Queueable Apex in Salesforce – Concept to Implementations

    Queueable Apex in Salesforce – Concept to Implementations

    INTRODUCTION

    Queueable Apex is an apex code that runs Asynchronously like a future method.

    Here the term Asynchronous means running in the background .

    Queueable apex and future method both run sdfs asynchronously but queueable apex provides these additional benefits.

    1. Getting Id of your Job:- ID JobId =system.enqueueJob(qe);
    2. Chaining Job:- In Queueable Apex we can chain one job to another.
    3. Using Non-primitive data types:-

    dont miss out iconDon’t forget to check: How to Write a Batch Apex in Salesforce

    Queueable is a interface whereas future is a method.

    1. These are used to run the long-running operations like external web-services call and bulk database operation asynchronously.
    2. If you want to run an apex class as a queueable apex then the Apex class has to implement a “queueable” interface.
    3. This interface adds jobs to the queue and observes them.
    4. Apex class has to define the execute method.
      .Syntax:public void execute(queueableContext qc){}
    5. Execute method in Queueable Apex is an Abstract method(with no definition) that execute the logic asynchronously.
    6. When we invoke the queueable job using the system.enquejob() method, this will return the id of the asynchronous job.using which we can track the status of the job.

    Example: With Queueable apex update the Account records and assign the jobid to description field of account.

    Apex Class:

    public class QueuableExample implements Queueable {    
        public void execute(QueueableContext qc){          
            List<Account> acc=[select id,Email__c,fax,phone,description from Account where industry='banking'];       
            for(account a:acc){            
                a.phone='+5555555555';        
                a.Email__c='Test@gmail.com';        
                string ids=qc.getJobId();       
                a.Description=ids;      
                update a;      
            }   
        }
    } 
    

    Anonymous Window: For Execution

    QueuableExample qe = new QueuableExample();
    system.enqueueJob(qe); 
    

    Example:Calling schedule apex from Queueabe apex.

    Queueable Apex:

    public class ChainingApex2 implements Queueable
    {       
        public void execute(queueablecontext qc1){        
            list<account> acc2=[select name,phone,industry,fax,sic from account where industry='banking'];     
            for(account b:acc2){          
                b.fax='143143143';     
                id x=qc1.getJobId();
                b.Sic=x;        
                update b;   
            }    
            ChainingApex1 ca=new ChainingApex1();    
            id ids=system.enqueueJob(ca);    
            Callschedule sa=new Callschedule();     
            string expression='0 34 16 7 12 ? 2017';   
            system.schedule('sctosc222',expression,sa);  
        }  
    } 
    public class chainingApex1 implements Queueable 
    {  
        public void execute(queueablecontext qc){        
            list<account> acc1=[select name,phone,industry,fax,description from account where industry='banking'];     
            for(account a:acc1){           
                a.phone='9999999';        
                id x1=qc.getJobId();     
                a.description=x1;       
                update a;     
            }  
        } 
    } 
    

    Schedule Apex:

    public class Callschedule implements schedulable 
    {     
        public void execute(SchedulableContext sc){    
            list<Account> accs=[select id,name from account where name='Test1' limit 10]; 
            for(account a:accs){             
                a.name='Test1';    
                update a;     
            }   
        }
    }
    

    dont miss out iconCheck out another amazing blog by Kirandeep here: Future Methods in Salesforce: An Overview

    GOVERNING LIMITS:

     Salesforce by default on every apex functionality imposed some limits to obey multi-tenant architecture. Governing Limits: 

    1. In every transaction maximum no. of SOQL statements: 100.
    2. In every transaction maximum no. of DML statements: 150. 
    3. In every transaction maximum no. of Records on which DML can be performed: 10,000.
    4. Every SOQL Query can return maximum: 50,000 Records. 
    5. In every transaction maximum no. of SOSL statements: 20. 
    6. In every transaction maximum no. of Future Methods: 50. 
    7. In every transaction maximum no. of Queueable call: 50. 
    8. In every transaction maximum no. of callouts: 100.
    9. In every transaction maximum no. of Email Invocations: 10