Ad
Ad
Ad
Tag

Slider

Browsing

61. What are different types of collections in Apex?

ListsA list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.

Sets–A set is an unordered collection of elements that do not contain any duplicates. Set elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.

MapsA map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.

62. What are different primitive datatypes used in Apex?

String, Integer, Boolean, Decimal, Date, Datetime

63. Is Apex Case sensitive?

Unlike Javascript, Lightning Webcomponents/Lightning Components, Apex is case Insensitive.

64. How are constants defined in Apex?

Constants can be defined using the final keyword.

Ex: static final Integer PRIVATE_INT_CONST = 200;

65. What does SOQL stand for and explain with an Example?

SOQL stands for Salesforce Object Query Language. This is used to query a list of records from the database.SOQL statements evaluate to a list of sObjects, a single sObject, or an Integer for count method queries.

List<Account> accnt = [SELECT Id, Name FROM Account WHERE Name = ‘salesforce’];

66. What are the Governor Limits on SOQL Queries?

Maximum number of SOQL queries issued in Synchronous(Trigger or Realtime) call is 100

Maximum number of SOQL queries issued in Asynchronous(Batch Apex, Queuable, Future) call is 200

67. How many records can be retrieved through a SOQL query?

Total number of records retrieved by SOQL queries is 50000

68.  What does SOSL stand for and explain with an Example?

SOSL stands for Salesforce object Search Language. SOSL always returns List of List of Sobject records.

SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the SOSL query. If a SOSL query does not return any records for a specified sObject type, the search results include an empty list for that sObject.

List<List<SObject>> searchList = [FIND ‘map*’ IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead];

69.What is the consideration for selective SOQL Query Criteria?

  • A query is selective when one of the query filters is on an indexed field and the query filter reduces the resulting number of rows below a system-defined threshold. The performance of the SOQL query improves when two or more filters used in the WHERE clause meet the mentioned conditions.
  • The selectivity threshold is 10% of the first million records and less than 5% of the records after the first million records, up to a maximum of 333,333 records. In some circumstances, for example with a query filter that is an indexed standard field, the threshold can be higher. Also, the selectivity threshold is subject to change.

70. Define Aggregate functions in Salesforce?

Aggregate functions in SOQL, such as SUM() and MAX(), allow us to roll up and summarize data in a query. Aggregate functions become a more powerful tool to generate reports when you use them with a GROUP BY clause. For example, you could find the average Amount for all your opportunities by campaign.

AggregateResult[] groupedResults= [SELECT CampaignId, AVG(Amount) FROM Opportunity  GROUP BY CampaignId];

for (AggregateResult ar : groupedResults)  {

    System.debug(‘Campaign ID’ + ar.get(‘CampaignId’));

    System.debug(‘Average amount’ + ar.get(‘expr0’));

}

51. If i have two triggers(Accttrigger and accounttrigger) on the Same object(Account) with
Same event(after insert), can i know which trigger will fire first?

No we cannot determine which trigger can be fired first. In order to control the execution, write a trigger per object and call an Apex class where we can control the Execution.

52. Can we Call a Future method from trigger?

Yes we can call a future method from trigger. This feature is helpful to call a Webservice /Callout process.

53. Can we invoke a Schedule Job from Trigger?

We can invoke a Schedule job from Trigger.

54. Can we invoke a Batch Apex class from Trigger?

We can invoke a Batch Class from Trigger

trigger acctTrigger on Account(before insert,before update){

AccountBatch accBatch = new AccountBatch();

Database.executeBatch(accBatch);

}

55. Can we Skip triggers for desired users or profiles in Salesforce?

We can skip triggers using Hierarchical Custom settings in salesforce for Desired profile.

56. When should we use before trigger vs after trigger?

As a groundrule, always use before triggers when you donot want to act on the Id of the record.Since before triggers doesnot require any DML it also helps in reducing DML and increasing performance compared to After Triggers. Use After triggers if we want to perform operations after the record is inserted(example Id is generated) and we want to perform operations on the child entities based on the record inserted. Ex: If we want to insert a contact record after an account is inserted then we need to write an After insert trigger on Account object and based on the account id we will insert the contact and associate Account id to it.

57.  Can we send Emails using Triggers?

Yes, We can send Emails using Triggers.The maximum number of Emails that could be sent is 5000 per org depending on Edition(Enterprise/Unlimited).

58. What are best practices in triggers?

a.Always write one trigger per object with all events.

b.For controlled execution write a trigger and call a Class and define methods in desired order.

c.Always write trigger to process a minimum of 200 records in single transaction

d. Avoid SOQL queries inside for loop as it will result in Governor Limits.

e. Avoid DML statements inside for Loop as it will result in Governor Limits.

59. Will the Triggers be fired if there is an workflow/process builder that performs an action?

Before update and After update triggers will be refired when a field update occurs from processbuilder/workflow.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_order_of_execution.htm

 Setup JEST unit Testing Framework for Lightning Web Components

In this post, We will try to learn to set up JEST unit Testing Framework for Lightning Web Components.

What is Jest ?

Jest is a powerful tool with rich features for writing JavaScript tests. Jest can collect code coverage information and supports mocking to help isolate tests from complex dependencies. Jest tests don’t run in a browser or connect to an org, so they run fast. Use Jest to write unit tests for all your Lightning web components. To run Jest tests for Lightning web components, you need the @salesforce/sfdx-lwc-jest Node module in your Salesforce DX project.

Installing SFDX-Jest

The following JSON is an example of the package.json . Before running the Jest installation setup command from the VSCode Terminal or the node module installation script please ensure that this json file is part of the VSCode SFDX project. The reason I say this is because this json file is parsed when the node module installation script is executed in a MS Windows OS based system.

Note: Always ensure the name attribute on the json matches the project folder name as seen on the Project Explorer in VSCode.

Before issuing the node based scripts, we need to ensure NodeJS is installed in our PC/Laptop. For this ensure you have NodeJS installation done by downloading the Windows equivalent installation file from NodeJs website. For Mac/Linux we can install the same through the terminals directly.

Once you are sure that NodeJS has been successfully installed, issuing the command sfdx force:lightning:lwc:test:setup on the VSCode terminal will result in a couple of warning deprecated details from npm. At times, in some Windows OS based machines we will get an error when this command is executed stating due to vulnerabilities it was not possible to complete the package installation in Windows based machines entirely. However, the screenshot does show that test setup got completed with vulnerabilities observed.

You can also run the script directly from where it was installed in the project using the following Node command. In the Visual Studio Code terminal, in the top-level directory of the Salesforce DX project, enter the following command.

node node_modules/@salesforce/sfdx-lwc-jest/bin/sfdx-lwc-jest

Doing this will setup the node_modules directory locally in the project directory wherever this node modules script is being executed.

While issuing the sfdx command in some of the SFDX projects the absence of the package.json file can result in the sfdx command sfdx force:lightning:lwc:test:setup failing. The error message would signify something like this:

Sometimes we may need to run the following commands in the destined order as mentioned below, to ensure lwc-jest gets installed and setup properly on Windows-based machines.

1st: npm install –global –production windows-build-tools

2nd : npm install @salesforce/lwc-jest –save-dev

Both the above commands can be run via GiT For Windows Shell or the PowerShell in a Windows based machine. For the above command ensure the PowerShell is run in the Administrator User’s context as follows by clicking on the Start menu button.

This step will ensure that lwc-jest framework has been successfully installed. This issue was faced by me when I was working on the LWC Unit Testing related Salesforce Trailheads. So I thought of covering up this topic on how I managed to fix the issue in this blog.

Automate Test Scripts with Package.json and npm

A goal of having unit tests is to promote developers to write and run them as part of their development and continuous integration process so that bugs are identified and fixed sooner rather than later. Having to remember and type long commands like the one above over and over is counterproductive to your goal. Here’s where automation comes in.

npm has some great out-of-the-box script automation flexibility. Running the install earlier added a series of options to the scripts property of the package.json file at the root of your project.

{

  “name”: “test-lwc”,

  …  “scripts”: {

“test:unit”: “sfdx-lwc-jest”,

“test:unit:watch”: “sfdx-lwc-jest –watch”,

“test:unit:debug”: “sfdx-lwc-jest –debug”,

“test:unit:coverage”: “sfdx-lwc-jest –coverage”,

  },

  …}

If you want to run all tests for your project, run this npm command from the base directory of your project.

npm run test:unit

Run Tests Continuously During Development

To run all tests for a single component every time you save changes, change directories to the component directory and run the npm command below that utilizes sfdx-lwc-jest with the –watch parameter. As mentioned above you could also run this from the base of the project and have all tests in the project run for every change. Git needs to be initialized for –watch to work from the command line.

npm run test:unit:watch

With Git initialized, Jest now watches all component files for updates and runs all relevant tests every time it detects a change.

Run Tests in Jest Debug Mode

To run the project’s Jest tests in debug mode, run the npm command below that utilizes sfdx-lwc-jest with the –debug parameter.

npm run test:unit:debug

Run Tests and Display Code Coverage

To see the code coverage of the tests, use the –coverage option below.

npm run test:unit:coverage

Post Contributor:

Rakesh Ramaswamy

https://www.linkedin.com/in/rakesh-ramaswamy-38062385/

In this post, we will try to Design a process using Custom Metadata settings to run the Batch job at desired intervals.

Custom Metadata Type – Schedule Batch Apex Jobs

This Custom Metadata Type is used to define how often the batch jobs must be executed. This custom metadata type can be used in the future for other batch jobs that will be newly developed in the course of the Salesforce Application Development.

CustomSettings

As seen in the illustration above, the custom metadata type comprises of 3 custom fields namely:

  1. Every X Minutes (API Name: Every_X_Minutes__c): This is a text field. If defined will ensure the batch job is executed every “X” Usually the value for “X” should be multiples of 5 and less than 60. For Eg: 20, 30, 40, 45.
  1. Execute Every Hour (API Name: Execute_Every_Hour__c): This is a checkbox field. If checked, will ensure the batch job is executed every hour in a day.
  1. Hour Of The Day (API Name: Hour_Of_The_Day__c): This is a text field. If defined will ensure the batch job is executed at the Hour of the day mentioned in this field. The hour should be mentioned in the 24-hour format and the values can range between 0 and 23. For Eg: If the batch must be scheduled to run at 1 PM by the scheduler job, then the hour to be mentioned in this field must be 13. Likewise, if it must be scheduled to run at 4 PM then the hour to be specified in this field must be 16.

Validation Rules on the Custom Metadata Type

Validationrule

The above validation rules can be defined on the Custom Metadata Type in order to ensure that multiple inputs aren’t provided when it comes to the batch scheduling time intervals. The intention for this solution to work is to ensure either the batch is configured to be run every “X” minutes, or every hour or at a specific time in the day. In Salesforce, the CRON Expression for scheduling the same would change every for each parameter that is being set depending on whether the batch has to be executed every “X” minutes or every hour in the day or at a specific time in the day.

Like for E.g.: Batch Job could be executed every hour in a day, or the Batch Apex Job could be executed once everyday at some specific time of the day. However, it is very unlikely that batches can be executed every 5 mins or every 10 mins. There may be possibility that batches would need to be executed ad-hoc typically in ISV product development scenarios. Even in that case it may so be the case that a Lightning or Salesforce Classic based button placed on a Lightning Page or Visualforce Page would be invoking the batch job ad-hoc.

Moreover, the downside or overhead of scheduling batch-jobs to run every 5 mins will result in the batch apex job running at different times as it moreover executes in an asynchronous manner. This can result in wrong outputs or results especially if we are calculating totals as aggregate or for that matter provisioning or revoking permissions in the form of permission-sets or share records.

 Setting CRON expression to run batch every ‘X’ Minutes.

As a developer, the idea is to ensure the Scheduler gets the right CRON job expressions each time it must invoke the batch apex job at the regular interval as expected. Always remember that, to execute the batch job every 30 mins the batch job would need to be invoked twice every hour, which technically implies that the scheduler will have to be invoked twice every hour.

System.schedule(‘SchedulerJob – ‘+String.valueOf(Math.abs(Crypto.getRandomLong())).substring(0, 5), ‘0 0 * * * ? ‘, new SchedulerJob());

System.schedule(‘SchedulerJob – ‘+String.valueOf(Math.abs(Crypto.getRandomLong())).substring(0, 5), ‘0 30 * * * ? ‘, new SchedulerJob());

With the above invocation, we will observe that the batch job gets scheduled for every 30 mins that is at the 60th minute or 0th minute of every hour and at the 30th minute in an hour. The Invoker class must call the Scheduler class twice so that the batch job gets called from the Scheduler Job.

System.schedule(‘SchedulerJob – ‘+String.valueOf(Math.abs(Crypto.getRandomLong())).substring(0, 5), ‘0 0 * * * ? ‘, new SchedulerJob());

System.schedule(‘SchedulerJob – ‘+String.valueOf(Math.abs(Crypto.getRandomLong())).substring(0, 5), ‘0 15 * * * ? ‘, new SchedulerJob());

System.schedule(‘SchedulerJob – ‘+String.valueOf(Math.abs(Crypto.getRandomLong())).substring(0, 5), ‘0 30 * * * ? ‘, new SchedulerJob());

System.schedule(‘SchedulerJob – ‘+String.valueOf(Math.abs(Crypto.getRandomLong())).substring(0, 5), ‘0 45 * * * ? ‘, new SchedulerJob());

In the above e.g. if let us say we set the custom metadata type in such a manner that we would like to run the batch job through the Scheduler Job, then in such a case the Scheduler will need to be invoked 5 times i.e. at 0th minute in the hour, 15th minute in the hour, 30th minute in the hour and at the 45th minute in the hour.

public class InvokeScheduler {

public void SchedulerMethod() {

     Schedule_Batch_Apex_Jobs__mdt scheduleBatchMDT = [SELECT Every_X_Minutes__c, Execute_Every_Hour__c, Hour_Of_The_Day__c FROM Schedule_Batch_Apex_Jobs__mdt WHERE DeveloperName = ‘Unique Name of the Custom Metadata Type data record‘];

     String CRON_EXPR;

     if((scheduleBatchMDT.Every_X_Minutes__c != null) || Test.isRunningTest()){                         

        if(Test.isRunningTest()){

         scheduleBatchMDT.Every_X_Minutes__c = ’20’;

        }

         list<String> CRON_ SubStringList = new list<String>();

         Integer X_MINS = Integer.valueOf(scheduleBatchMDT.Every_X_Minutes__c);                                                                   

         Integer Interval = Integer.valueOf(60/X_MINS);

         system.debug(‘*** Interval ===> ‘+Interval);

         if(Interval == 1){

             Interval += 1;

         }

         Integer seriesVal = X_MINS;

         Integer seriesCount = 0;

         for(Integer i = 0; i < Interval; i++){ 

             seriesCount += seriesVal;

             if(seriesCount < 60){

                 CRON_SubStringList.add(String.valueOf(seriesCount));

             }

         }

         for(String schedulerMinsInterval : CRON_ SubStringList){

             CRON_EXPR = ‘0 ‘+schedulerMinsInterval+’ * * * ?’;               

             scheduleBatch.scheduleMe(CRON_EXPR);

         }

     }

     if((scheduleBatchMDT.Execute_Every_Hour__c != false) || Test.isRunningTest()){                       

         CRON_EXPR = ‘0 0 * * * ?’;

         system.debug(‘*** I am going to execute the batch every hour ****’);

         scheduleBatch.scheduleMe(CRON_EXPR);

     }

     if((scheduleBatchMDT.Hour_Of_The_Day__c != null) || Test.isRunningTest()){                    

         if(Test.isRunningTest()){

             scheduleBatchMDT.Hour_Of_The_Day__c = ’21’;

         }

         CRON_EXPR = ‘0 0 ‘+scheduleBatchMDT.Hour_Of_The_Day__c+’ * * ?’;

         scheduleBatch.scheduleMe(CRON_EXPR);

     }                              

}

}

The above class is the invoker class that ensures that several instances of the scheduler are instantiated to run at the specific time in regular intervals. This class is responsible for preparing the CRON expression that will define how often the Scheduler Jobs must be instantiated, which in turn will be responsible for invoking the batch. Before calculating the CRON expression it is important to understand what setup as part of the metadata-type has been configurational settings.

The Interval variable is being used to identify the iterations we need to go through to build on the CRON Expression. CRON_ SubStringList must be a list collection to determine the series in minutes how often the scheduler must be scheduled because the list collection helps us get the string in an ordered manner vs. a set collection because the set is an unordered collection.

Can we call the Scheduler class from the Scheduler class itself (Recursion calls)?

We Cannot do this because the Scheduler goes into an infinite loop of a never-ending state and keeps spawning new processes.  Some blogs also suggest to hit the CRONTrigger repository table to find the immediate last scheduler’s Job ID and to abort it. This will not be the actual solution to this problem. This is the very reason it makes sense to control the Scheduler job invocation from an external class, which in this case will be the InvokeScheduler Apex Class.

global class scheduleBatch implements Schedulable {             

global static void scheduleMe(String CRON_EXPR) {

     System.schedule(‘ Schedule Job – ‘+String.valueOf(Math.abs(Crypto.getRandomLong())).substring(0, 5), CRON_EXPR, new scheduleBatch());

}

global void execute(SchedulableContext sc) {

    Database.executeBatch(new actualBatchJobName(), 200);    

}    

}

The above Apex class is none other than the actual Scheduler Class that is implementing the Schedulable interface. This class has two methods one is the execute( ) method that runs in the Schedulable Context and the other i.e. scheduleMe() is the static method which is invoked from the InvokeScheduler class, to ensure the scheduler is instantiated dynamically depending upon the no of instance that has to be spawned based on the Custom Metadata Type setup.

Post Contributor:

Rakesh Ramaswamy

https://www.linkedin.com/in/rakesh-ramaswamy-38062385/

41. What is Recursion and when does this issue occur?

Recursion is the process of executing the same piece of code infinite times. Eventually, this will result in hitting Governor limits in Salesforce. This issue occurs when we have an after Update Trigger event along the Process builder/Workflow field update acting on the Same field.

Example: If we have an After update trigger on Opportunity that is trying to Update a stage field and we also have a process builder/workflow on Stage field this will result in Recursion as the trigger update will fire the Process builder/workflow and process builder/workflow is again going to invoke trigger. This will keep on executing infinite times and eventually, the process results in hitting governor Limit.

hitting governor Limit.

42. How to avoid Recursion in Salesforce?

We can avoid recursion in Salesforce by using a static helper method. Read below for complete details of Recursion

43.  What is DML in salesforce?

DML(Data Manipulation Language) in Salesforce provides the ability to manage records using insert, Update, Delete and Restore statements

44. What are different DML Statements in Salesforce?

insert,update,upsert,delete,undelete,merge

45. What is the difference between update and upsert?

update statement helps in updating the record based on recordId. Upsert DML statement creates the record if there is no existing record and if a record exists then it will update the record.

46. Will any records be deleted during merge process?

The merge statement merges up to three records of the same sObject type into one of the records, deleting the others, and re-parenting any related records.

47. What are different Database methods in Salesforce?

  • Database.insert()
  • Database.update()
  • Database.upsert()
  • Database.delete()
  • Database.undelete()
  • Database.merge()

48. What is difference between DML Statements and Database methods?

Unlike DML statements, Database methods have an optional allOrNone parameter that allows you to specify whether the operation should partially succeed. When this parameter is set to false, if errors occur on a partial set of records, the successful records will be committed and errors will be returned for the failed records.

Note: No exceptions are thrown with the partial success option.

49. Can i insert partial records in a Transaction?

Yes we can insert partial records in a transaction using Database method with allorNone parameter set to false.

Ex:  Database.SaveResult[] results = Database.insert(recordList, false);

50. Please provide a sample code that process partial records in salesforce?

Execute the below piece of code in Execute Anonymous window of Developer Console

// Create a list of contacts

List<Contact> conList = new List<Contact> {

        new Contact(FirstName=’Joe’,LastName=’Smith’,Department=’Finance’),

        new Contact(FirstName=’Kathy’,LastName=’Smith’,Department=’Technology’),

        new Contact(FirstName=’Caroline’,LastName=’Roth’,Department=’Finance’),

        new Contact()};

// Bulk insert all contacts with one DML call

Database.SaveResult[] srList = Database.insert(conList, false);

// Iterate through each returned result

for (Database.SaveResult sr : srList) {

    if (sr.isSuccess()) {

        // Operation was successful, so get the ID of the record that was processed

        System.debug(‘Successfully inserted contact. Contact ID: ‘ + sr.getId());

    } else {

        // Operation failed, so get all errors

        for(Database.Error err : sr.getErrors()) {

            System.debug(‘The following error has occurred.’);

            System.debug(err.getStatusCode() + ‘: ‘ + err.getMessage());

            System.debug(‘Contact fields that affected this error: ‘ + err.getFields());

}

    }

}

In this post, We will try to understand how to use a ternary operator in salesforce to reduce code. Ternary Operator acts as a short-hand for if-then-else statements.

x ?  y  : z

If x a boolean is true then the result will be y and If x a boolean is false then the result will be z.

Integer result= Condition? Valueone : Valuetwo;

Example(Ternary):

Integer currentmarketPrice = 25000;

Integer priormarketPrice = 15000;

Integer OppAmount = priormarketPrice > 15000 ? currentmarketPrice : priormarketPrice ;

If we do not use a ternary operator then we would have ended up implementing If then else logic with multiple lines of code.

Example(Without Ternary operator/If-else logic):

Integer OppAmount;

Integer currentmarketPrice = 25000;

Integer priormarketPrice = 15000;

If(priormarketPrice > 15000 )

{

OppAmount = currentmarketPrice;

} else {

OppAmount = priormarketPrice;

}

In this post, We will try to understand the key difference between With Sharing and without Sharing in Salesforce.

With Sharing Keyword: Apex by default runs in System mode or Admin mode. In Admin mode the class will have all the access to the field and object irrespective of running user’s permission. Any class that has With Sharing will enforce the Sharing rules for the current user. This has to be explicitly specified while writing the class as by default the class will have without sharing.

For Example: If a user with a Standard profile has access to Name or Address field on Account object then he/she will be able to only insert/update only Name and Address field. He/she will not be able to insert/update other fields as they do not have access to other fields as per profile access.

public with sharing class AccountsharingClass {

}

Without Sharing Keyword: Apex by default runs in without Sharing mode(ie admin mode/System mode).In Admin mode the class will have all the access to the field and object irrespective of running user’s permission. We could also explicitly specify without sharing keyword to ensure sharing rules are not imposed for the current user.

public without sharing class AccountsharingClass {

}

Note: If a method is defined in a class declared with with sharing is called

by a class declared with without sharing, the method executes with sharing 

rules are enforced. Ex: Lets assume we have two classes,Class A is created with

 “with sharing” and Class B iscreated with “without sharing”. If We call class A

from Class B then with sharing rules will be applied.

In this post, We will try to understand how to initiate Batchjob from Other Batch Job. Every Batch job consists of three methods such as Start, Execute, and Finish methods.

In the start method, we will query for the list of records from the desired object. Generally, We use Querylocator as it could hold up to 50 million records.

Execute method – All the business logic is processed inside the Execute method by using the list of records from the Start method

Finish method – This is the last method inside batch apex which will be executed after the Execute method. We could send an Email or Call a Batch job or do both inside this method.

Ex: We have two Batchjobs such as AccountBatch and ContactBatch.We could call ContactBatch from the finish method of AccountBatch

global class AccountBatch implements Database.Batchable<sObject>

{

    global Database.QueryLocator start(Database.BatchableContext BC)

    {

        String query = ‘SELECT Id,Name FROM Account’;

               return Database.getQueryLocator(query);

    }

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

    {

       List<Account> accList = new List<Account>();

     for(Account acc : scope)

        {

            acc.Name = “Account Processed”;

            accList.add(acc);

        }

        update accList;

    }

    global void finish(Database.BatchableContext BC)

{

// Call Contactbatch job from AccountBatch

    ContactBatchJob contactJob = new ContactBatchJob();

   database.executebatch(contactJob);

    }

}

In this post, We will try to understand how to schedule a batch job in Salesforce to run every 30 mins. Salesforce User interface gives us the ability to only Schedule Apex classes on an hourly basis. If we want to schedule our batch class to run every 30 mins or to run at 12:30/1:30/2:30/3:30  this is not possible from user interface.

We could achieve the desired functionality from developer console. Run the below command to schedule the job to run for every 30 mins

Command for 30 mins:

system.schedule(‘AccSched30min’, ‘0 30 * * * ?’, new AccountSchedule());

Command for 15 mins:

system.schedule(‘AccSched15min’, ‘0 15 * * * ?’, new AccountSchedule());

Command for 45 mins:

system.schedule(‘AccSched45min’, ‘0 45 * * * ?’, new AccountSchedule());

Command for 10 mins:

system.schedule(‘AccSched10min’, ‘0 10 * * * ?’, new AccountSchedule());

From Schedule Jobs check for the jobs that were scheduled.

In this post, we will try to understand what causes “Too many SOQL Queries 101 error”. Salesforce is a multi-tenant environment(Multiple client orgs are run on the Same server) as a result there are some limitations enforced by Salesforce to make sure all clients utilize the platform efficiently. As part of this process, Salesforce imposes Governor limits on its clients to make sure all the orgs adhere to salesforce guidelines.

Too many SOQL Queries 101 error is a governor limit imposed by Salesforce and this issue appears when we write our query inside for Loop. The maximum number of queries allowed in a Single transaction is 100 queries. The number 100 looks to be a huge number but we could hit this number very easily in a Single transaction if we do not write our code efficiently.

Inefficient Code: The below code cause “Too many SOQL Queries 101 error” when we load more than 100 records in a single transaction. Note: By default, triggers process 200 records at a time.

for(Contact con: trigger.new)

{

List<Account> AccountList =[Select id,Name from Account where id=:con.AccountId];

}

Efficient Code: Remove the Query inside the for loop and write it outside the loop.

List<String> AccidList =new List<String>();

for(Contact con: trigger.new)

{

AccidList.add(con.accountId);

}

List<Account> AccountList =[Select id,Name from Account where id=:AccidList];