Monday 22 May 2017

Salesforce Interview Questions-Validation Rules




1. What are validation rules?
Validation rule contains an error condition and error message. If evaluation of error condition results in true value, record is not saved, and the error message is generated. Validation rules can be attached to fields. They are executed when a record is created or updated.

2. Can we avoid deletion of records through validation rules?
No. Validation rules fire in insert and update operation.

3. Can we bypass validation Rules?
Validation rules can never be bypassed. If we have upload records and need to bypass validation, then deactivate validation rule and upload records. After upload, again activate validation rule.

4. Is it possible to fire validation only for records which is being getting updated not to newly inserted records?
Yes, We can use ISNEW() function which will return true whenever new record is getting created in validation rule. We can use this function and check our criteria only if ISNEW() function is returning false(means record is being updated).

5. Is there is any way through which validation rule is bypassed while doing upload through data loader but not when user is creating record from user interface?
Yes. Create a checkbox field as API upload and make this field hidden in page layout. Create a validation rule and in evaluation criteria first check if checkbox is false and then check other validation criteria.
Whenever user upload record through data loader, specify value for this checkbox as true in .csv file and then upload it to salesforce. While upload, validation rule will fire and will find checkbox value as true so it will not check other criteria and system will allow to upload records.

6. What is the difference between ISBLANK() AND ISNULL()?
ISNULL() works only for number data type fieds, if we don't populate with value for number fields it will return true.
ISNULL() won't support TEXT data type fields because text fields never become null.
ISBLANK() supports both number as well as text data types.

7. What are cross object formula fields?
Cross-object formulae span two or more objects by referencing merge fields. By using this you can refer parent fields from child record.

8. What are different ways to make field required in salesforce?

While field creation, specify required field as true.
Through page layouts
Validation rule
Apex trigger9. Admin wants to avoid the deletion of child records in master detail relationship. Is it possible to achieve this using point and click functionality?
Yes. First create a roll up summary field on parent which calculates the total count of child records. Now write a validation rule on parent object which checks if previous value of total count is less than new value. If yes, then display error message.
Suppose field name is total_count__c in parent object then validation rule criteria will be:
Priorvalue(total_count__c) <total_count__c
When we delete the child record then roll up summary field value will get reduced by 1. System will update the parent record roll up summary field which will fire the validation rule and avoid user from deleting child record.

Sunday 21 May 2017

Using Database.upsert with external ID field


Using Database.upsert with external ID field
External Id plays very important role if you want to update records without knowing the record Ids or want to relate the child record with parent record without knowing the parent record Id.

As a best practice, you should always make External Id unique. If you are performing upsert with External Id, then following situations will occur:


If no record is found in table with provided External Id, then it will create record in table.
If 1 record is found in table with provided External Id, then it will update record in table.
If more than 1 records is found in table with provided External Id, then system will throw an error.
I am going to cover 2 different aspect of using external Id in apex.


Updating a record with External Id


Create a External Id field on Account as Account_Unique_Number__c and mark it as External Id and unique while creating it.Now we will create a new record using upsert.


Execute below command in developer console


List<Account> acclist=new list<Account>();
acc.name='Demo test1';
acc.Account_Unique_Number__c='00001';
acclist.add(acc);
Schema.SObjectField ftoken = Account.Fields.Account_Unique_Number__c;
Database.UpsertResult[] srList = Database.upsert(acclist,ftoken,false);
for (Database.UpsertResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('error has occurred.' + err.getStatusCode() + ': ' + err.getMessage());
System.debug('fields that affected this error: ' + err.getFields());

}
}
}


As there is no record in Account with Account_Unique_Number__c as 00001, system will create a new record.


Now again we will run same script in developer console and will specify some more field values:


List<Account> acclist=new list<Account>();
Account acc=new Account();
acc.name='Demo test1';
acc.Account_Unique_Number__c='00001';
acc.type='Other';
acc.Industry='Banking';
acclist.add(acc);
Schema.SObjectField ftoken = Account.Fields.Account_Unique_Number__c;
Database.UpsertResult[] srList = Database.upsert(acclist,ftoken,false);
for (Database.UpsertResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('error has occurred.' + err.getStatusCode() + ': ' + err.getMessage());
System.debug('fields that affected this error: ' + err.getFields());

}
}
}


Now you will see that system will update the record as it was able to find a Account record with Account_Unique_Number__c as 00001

Relating a child record with parent record by using parent record Id


In order to understand this, we will create contact record and will relate to account using Account_Unique_Number__c. Execute below code in developer console:

List<Contact> conlist=new list<Contact>();
Contact con=new Contact();
con.lastname='Kumar';
con.Firstname='Kumar';
con.email='sunil02kumar@gmail.com';
Account acc=new Account(Account_Unique_Number__c='00001');
con.Account=acc;
conlist.add(con);
Database.UpsertResult[] srList = Database.upsert(conlist,false);
for (Database.UpsertResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('error has occurred.' + err.getStatusCode() + ': ' + err.getMessage());
System.debug('fields that affected this error: ' + err.getFields());
}
}
}


This will create a new contact for Account which have Account_Unique_Number__c as 00001.


In above code snippet, you can see that in order to relate contact with account, we are not specifying the account 15 or 18 digit record id. We are just specifying the external Id of account and system will maintain the relationship.


Why it is recommended to mark External Id as unique?


Imagine you are creating a contact and specified External Id of parent. Suppose there are 2 records in account table with same value, then system will not able to identify with whom it needs to relate the contact and will throw error saying more than 1 match found.

Same is applicable when you update the record with External Id.

Salesforce Interview Questions-Sharing & Security Part-1




  • 1. What are different levels of security in salesforce?


  • Object level security
The bluntest way that we can control data is by preventing a user from seeing, creating, editing, and/or deleting any instance of a particular type of object, like a Position or Review. Object-level access allows us to hide whole tabs and objects from particular users, so that they don't even know that type of data exists.
On the platform, we set object-level access rules with object permissions on user profiles.
  • Field level security
A variation on object-level access is field-level access, in which a user can be prevented from seeing, editing, and/or deleting the value for a particular field on an object. Field-level access allows us to hide sensitive information like the maximum salary for a position or a candidate's social security number without having to hide the whole object.
On the platform, we set field-level access rules with the field-level security.
  • Record level security
To control data with a little more finesse, we can allow particular users to view an object, but then restrict the individual object records that they're allowed to see. For example, record-level access allows an interviewer like Melissa Lee to see and edit her own reviews, without exposing the reviews of everyone else on her team.
On the platform, we actually have four ways of setting record-level access rules:
Organization-wide defaults
Role hierarchies
Sharing rules
Manual sharing
2. What is Organization wide default?

OWD stands for Organization wide defaults. This setting is defined at object level. OWD defined the default record level sharing for objects. All profiles get at least the privileges defined in OWD. OWD takes three different values -

A. Private
B. Public Read only
C. Public Read-WriteTo find out what should be set as OWD for an object, first find out which user requires least access to an object. OWD is set based upon this users access requirements.
Most restrictive record access is defined using OWD. Access to additional records is made available through Role hierarchy, Sharing rules, Manual sharing.

3. What is role hierarchy?

Role Hierarchy allows additional users access to records. A hierarchy of roles is defined based upon access requirements at record level. Each user belongs to a unique role. If a role has access to some record, than its parent and ancestors will also have access to this record. Roles can be created using the Manager Users menu. Roles are used to control record access, where as profiles are used to specify access at object and field level.

4. What is public group?

Public group consists of users, roles or "roles and subordinates". Sharing rule is defined using public groups. Record that match certain condition can be assigned to users in public groups using Sharing Rules. Sharing rules functionality is available via the menu Sharing Settings.

5. What is manual sharing (User Managed Sharing)?

Manual Sharing is used to grant one-off access. Manual sharing can be granted by record owner, any one above the owner in role hierarchy and System Administrator. Manual sharing is used to handle exception cases where access to a particular record needs to be given to a specific user. There is a Sharing button on the records page. This is used to provide manual sharing.

Finding RecordType access to different profiles by using Metadata API




Consider a scenario in which you have an object which is having more than 10 recordtypes. Now you need to find out which all profiles have access to which recordtype. In order to achieve this, admin has to go to each profile and check the recordtype access. Imagine if you have more than 10 profiles which have access to different recordtype of this object.

In order to avoid this manual effort, I have created a VF page where user can select object and particular profile or all profiles and can see the result on a report. I am using metadata API to achieve this.

Please find below unmanaged pakage installation URL:

https://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000NPA0

Or you can download the code from Git by using below URL:

After installation, open tab "RecordType Access Finder". You may get "Unauthorized endpoint URL".



Add endpoint URL to remote site setting.

After opening the tab, select the object and profile for which you want to get report for recordtype access to different profiles. You can also specify "All" for profiles.





If you are getting some error by selection all profiles and clicking on "Retrieve and generate report" button, then it means you profile metadata file size is more so in this case, select one profile at one time and click on "Retrieve and generate report" button.
After this operation is finished, then select another profile and again click on "Retrieve and generate report" button. Repeat same process for all profiles you want to check.

Now click on report link and you will be redirected to SFDC standard report where you can see different recordtypes assigned to different profiles.


Asynchronous Apex- Apex Scheduler, Batch Apex & Future Methods Implementation Tricks





Salesforce provide different options to run asynchronous jobs which can run in background whenever salesforce resources will be available.
  •  Apex Scheduler is one of the options through which you can schedule a job to run after certain interval of time or to run at particular time everyday, every week, every month etc.

  • Batch Apex allows you to process large volume of data. Normal apex class will hit governor limits if we process large volume of data. Batch Apex split the records in different batched and you will get new governor limits for each batch.

  • Future methods runs asynchronously which can be used to perform some operation in background. When you are executing particular code and you want to perform some other operation and don't want to wait for it to get completed, then you can use future method to perform that operation and you can continue executing your code. You can consider that future methods starts new thread or execution.




  1. Now we are going to cover different scenarios related to future methods and apex schedulers and batch apex.

  • Is it possible to call future method from apex scheduler or not?
  • Yes
  1. Below is sample code which I tested for this scenario. After scheduling the scheduler, I checked the debug logs and it was displaying logs for future handler and debug statement present in future method was present in logs.
//Scheduled Apex
public class DemoScheduler1 implements Schedulable{
public void execute(SchedulableContext sc){
system.debug('*******Going to call future method ');
DemoAsynchronousTest.futureMethodCallFromScheduler();
}
}


//apex class containing future method
public class DemoAsynchronousTest{


@future
public static void futureMethodCallFromScheduler(){
system.debug('******futureMethodCallFromScheduler get called');
}

}


  • Is it possible to do Synchronous Web service callouts from scheduled apex? 
  • No.
Synchronous Web service callouts are not supported from scheduled Apex. To be able to make callouts, make an asynchronous callout by placing the callout in a method annotated with @future(callout=true) and call this method from scheduled Apex. However, if your scheduled Apex executes a batch job, callouts are supported from the batch class.

  • Can we call scheduler from future method?
  • Yes
  • Can we call future method from batch apex (from execute method)?
  • No
Is there is any way through which we can call future method from batch apex?
As we know that a webservice can be called from batch class and webservice can call @future method. So in your batch class call webservice and which can call your @future method.


Also you can call future method from finish method in batch class.
What all different things which we need to consider while using future methods?
Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor.
You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a trigger from an annotated method that calls another annotated method.
Future methods cannot be called from batch class.

  • Can we modify the scheduler class or classes referenced by this scheduler class if any scheduled job is pending?
  • No

If there are one or more active scheduled jobs for an Apex class, you cannot update the class or any classes referenced by this class through the Salesforce user interface. However, you can enable deployments to update the class with active scheduled jobs by using the Metadata API.

What we can do if we have to deploy the scheduler class or classes referenced by this scheduler class if any scheduled job is pending for that scheduler class in target org?

By default, changes to Apex code that have Apex jobs pending or in progress can’t be deployed. To deploy these changes, do one of the following.
Cancel Apex jobs before deploying changes to Apex code. Reschedule the jobs after the deployment.
Enable deployments with Apex jobs in the Salesforce user interface in the Deployment Settings page.






Monday 6 February 2017

Display Helptext In Visualforce Page In Less Time, Check this out

Display Helptext In Visualforce Page In Less Time, Check this out

Whenever we override our salesforce standard page with custom page i.e. by visual force page, there is always be clients/Users many time demand for same Standard page layout inline Help Text bubbles.

The help text that is displayed next to this field as a hover-based tool tip, similar to the text that is displayed next to standard Salesforce fields if custom help is defined for the field in Setup.


Syntax to display Help Text:

{!$ObjectType.objectName__c.Fields.fieldName__c.inlineHelpText}

Create Visual force page: Copy and paste below sample code and click on Save button

<apex:page standardController="Account">
  <apex:pageBlock >
    <apex:form >
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem helpText="{!$ObjectType.Account.Fields.LightingNitish__Account_Address__c.InlineHelpText}">
                <apex:outputLabel value="{!$ObjectType.Account.Fields.LightingNitish__Account_Address__c.Label}" />
                <apex:inputField value="{!Account.LightingNitish__Account_Address__c}" />
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:form>
  </apex:pageBlock>
</apex:page>


Click on Preview button of visualforce page
Or 
You can Go to the URL and type (Change the yoursalesforceinstance with your salesforce org URL) and add any account valid record id.


https://yoursalesforceinstance.com/apex/VisualForcePageName.

Output:



Note: If you use "showHeader=false" in <apex:Page> then helpText is not displayed.

Here in above code you might confuse about field LightingNitish__Account_Address__c. 
LightingNitish__Account_Address__c is a combination of namespace and API name.
LightingNitish is my org namespace and then Account_Address__c custom field API name.

Other way to help text in Visual force page:



1. <apex:inputField> and <apex:outputField> shows help Text bubble when nested within a <apex:pageBlockSection> component automatically.
but in order to do this, you need to include a <apex:PageBlockSection> nested in a <apex:PageBlock>tag as well.

However, there are two scenarios where helpText Bubble is not displayed in the VisualForce page.

  1. If we use "Label" attribute of <apex:outputField> , then helpText bubble is not displayed in visualforce page.
  2. If we set "showHeader=false"  of <apex:Page>, in that case also helpText bubbles is not displayed in visualforce page.
Here I came up with my own idea to display help text at VF page with above two scenarios:


<div id="mainAccountContent">

    Sample help Text Example

    <span class="CustomHelpTextExample">

<img src="/HelpTextExample.gif" alt="Help" class="helpIcon" title="$ObjectType.Account.Fields.LightingNitish__Account_Address__c.InlineHelpText"/>

    </span>
</div>

By Providing "$ObjectType.Account.Fields.LightingNitish__Account_Address__c.InlineHelpText" in TITLE attribute of <img> tag.
The helpText will be displayed as ToolTip Text.

You do not need to use <apex:PageBlockSection> tag.

Also in above code I used field LightingNitish__Account_Address__c. 
LightingNitish__Account_Address__c is a combination of namespace and API name. LightingNitish is my org namespace and then Account_Address__c custom field API name.

2. Use the <apex:pageBlockSectionItem> with attribute helpText filled. 
You can then "override" it or better say use you own custom help text independent of another one from the custom field:

<apex:pageBlock>
    <apex:pageBlockSection>
        <apex:pageBlockSectionItem helpText="Your custom help text.">
            <apex:outputLabel value="Account Name"/>
            <apex:inputText value="{!Account.Name}" />
        </apex:pageBlockSectionItem>
    </apex:pageBlockSection>
</apex:pageBlock>

It looks like this then:


3. Display help text entered in the custom field under "Help Text". This text appears if you use a pageBlock together with an outputField:

<apex:pageBlock>
    <apex:pageBlockSection>
        <apex:outputField value="{!Account.Account_Address__c }" />
    </apex:pageBlockSection>
</apex:pageBlock>

Run Schedule a Class In Every 5 Mins in Salesforce

Run Schedule a Class In Every 5 Mins in Salesforce

By default you can run apex job every 1 hour using CRON expression but you can schedule this job 12 times at 5 min duration.

If you are not aware of Schedulable Batch Apex then first look Schedulable Batch Apex In 3 Easy steps In Salesforce

Then how to Schedule a Class in Every 5 Mins in Salesforce, since this is not possible to do through standard Salesforce User interface.

Yes I have solution for it. So here is a small code to do so for every 5 minutes.

Example, you have Scheduler class namely ScheduleBatchApexClassExample and want to run the schedule a class in every five mins, then use below CRON expression.

How to run follow below process:


Go to your developer console -> Open Execute Anonymous Window -> Copy and Paste Below code and click on execute button

Simply say, Run below CRON expression from your developer console:


System.schedule('Schedule Job Name 1',  '0 00 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 2',  '0 05 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 3',  '0 10 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 4',  '0 15 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 5',  '0 20 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 6',  '0 25 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 7',  '0 30 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 8',  '0 35 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 9',  '0 40 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 10', '0 45 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 11', '0 50 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 12', '0 55 * * * ?', new ScheduleBatchApexClassExample());

After this, if you want To check apex class in scheduled or not then:

Export VisualForce Data into Excel Sheet in 3 Easiest Steps

Export VisualForce Data into Excel Sheet in 3 Easiest Steps

One of the most common Business requirements is to export a VisualForce page with data into an Excel sheet.

If you want to import CSV file In Salesforce using Apex then check Import CSV file In Salesforce using Apex in 3 Easiest Steps

Here in this blog, I am exporting contact data into AllContacts.xls sheet using Visualforce page.

To export data from a Visualforce page, the only real change that you have to make to the page is to change the content type of the page to “application/vnd.ms-excel” and also set a file name. 
<apex:page contentType=”application/vnd.ms-excel#AllContacts.xls”> </apex:page>

By simply modifying the ContentType attribute on the <apex:page> tag, your Visualforce page code will automatically generate an Excel document and download it automatically. 

For example, the following code will create a table of Contact data for a given Account. After # in the contentType attribute value, it is the name of the excel file that will be generated and you also need to mention the file extension like .xls.

Here is the sample code:

Step 1:


To do this, lets start off with a super simple controller. Create Apex Class ExportAllContactsHandler

public class ExportAllContactsHandler{
    public List<Contact> lstContact {set;get;}
   
    public ExportAllContactsHandler(){
        // Here I added limit 10, you can add filter criteria which you want
        lstContact = [Select Id, Name, Email, Phone From Contact Limit 10];   
    }

}

Step 2: 

Create Visualforce Page with name Export_All_Contacts:

<apex:page controller="ExportAllContactsHandler" contentType="application/vnd.ms-excel#AllContacts.xls" cache="true">
    <apex:pageBlock title="Export All Contacts">
        <apex:pageBlockTable value="{!lstContact}" var="objContact">
            <apex:column value="{!objContact.Name}"/>
            <apex:column value="{!objContact.Email}"/>
            <apex:column value="{!objContact.Phone}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

Step 3:

You can click on Preview button which is on Visualforce page 
OR 
You can Go to the URL and type (Change the yoursalesforceinstance with your salesforce org URL)

https://yoursalesforceinstance.com/apex/Export_All_Contacts

AllContact.xls downloaded automatically into your local system.

When you have created this Visualforce page and you go to view the page, your browser should automatically download the .xls file. When you try to open it, you will most likely be presented with an error!
Click OK and open the file.

Its very simple code here. You have to keep only 1 things in your mind while Export VisualForce Data into Excel Sheet.
Here in query, I have added LIMIT statement in the controller to limit the Contact returned to 10. If your Salesforce org have 10000 contacts then you will face issue like, "Collection size xxxx exceeds maximum size of 1000".
We should always limit the query here so as not to reach the View State limit, but in this case it is done to to keep the file returned nice and simple for later processing. 
What are the Best practices to optimize view state, then check this : An Introduction to Visualforce View State in Salesforce

Import CSV file In Salesforce using Apex in 3 Easiest Steps

Import CSV file In Salesforce using Apex in 3 Easiest Steps

Salesforce does not read the excel file into apex. To overcome for this either we can covert excel file to CSV and import csv file using below code.

We can import data using data loader But sometime there is requirement when end users do not want to use Apex Data loader. 

Client want custom page to load data in salesforce.

Here I am explaining Import CSV file In Salesforce using Apex. Below is the code snippet which import CSV file from apex. I have created one visual force page and controller associated with it. 

Visual force page have Import Accounts into Salesforce button. 
Once user click on the button, I am sending email using apex code. 

Step 1: Create Apex Controller

public class importDataFromCSVController {

  public Blob csvFileBody{get;set;}
  public String csvAsString{get;set;}
  public String[] csvFileLines{get;set;}
  public List<account> accountlist{get;set;}

  public importDataFromCSVController(){
    csvFileLines = new String[]{};
    accountlist= New List<Account>(); 
  }
  
  public void importCSVFile(){
       try{
             // Read CSV file body and store it in variable
              csvAsString = csvFileBody.toString();
   
            // Split CSV String to lines
             csvFileLines = csvAsString.split('\n'); 
           
            // Iterate CSV file lines and retrieve one column at a time.
             for(Integer i=1; i < csvFileLines.size(); i++){
               Account accObj = new Account() ;
               String[] csvRecordData = csvFileLines[i].split(',');
               accObj.name = csvRecordData[0] ;             
               accObj.accountnumber = csvRecordData[1];
               accObj.Type = csvRecordData[2];
               accObj.AccountSource = csvRecordData[3];   
               accObj.Industry = csvRecordData[4];                                                                             
               accountlist.add(accObj);   
             }
            // if all correct then insert Account into Org
             if(accountlist.size()>0)
             insert accountlist;
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importing data into Salesforce. Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);
        }  
  }
}

Step 2: Create Visual force Page

<apex:page controller="importDataFromCSVController" sidebar="false" showHeader="false">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection columns="4"> 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Import Accounts into Salesforce" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!accountlist}" var="acc">
              <apex:column value="{!acc.name}" />
              <apex:column value="{!acc.AccountNumber}" />
              <apex:column value="{!acc.Type}" />
              <apex:column value="{!acc.Phone}" />
              <apex:column value="{!acc.Fax}" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>

Step 3: Download csv file into local machine. Click here to download CSV file.

Schedulable Batch Apex In 3 Easy steps In Salesforce

Schedulable Batch Apex In 3 Easy steps In Salesforce

  • There are three main steps involved in this

1. Write Batch Class
2. Write a Scheduled Apex which execute the above Batch Class
3. Schedule the class from the Developer Console or from UI

So here we go...

Step 1. Write Batch Class

global class BatchApexClassExample implements Database.Batchable<SObject>{

 global Database.QueryLocator start(Database.BatchableContext BC) { 
  String soqlquery = 'SELECT Id, name, phone FROM Account';
  return database.getquerylocator(soqlquery);
 }
 // The batch job executes and operates on one batch of records
 global void execute(Database.BatchableContext BC, List<SObject> scope) { 
   // your logic
   System.debug('In BatchApexClassExample - Execute Method ');
 }
 // The batch job finishes
 global void finish(Database.BatchableContext BC) { 
   System.debug('BatchApexClassExample Batch job completed successfully.');
 }
}

Step 2. Write a Scheduled Apex which execute the above Batch Class

global with sharing class ScheduleBatchApexClassExample implements Schedulable {
 global void execute(SchedulableContext sc) {
  ID BatchId = Database.executeBatch(new BatchApexClassExample(), 200);
 }
}

Step 3. Schedule the class from the Developer Console or from UI
  •  From UI : Go to Setup -> Apex Classes -> Click on Schedule Apex button
  •  From Developer Console, check below 
 Execute a schedulable Apex class with System.schedule method

 System.schedule('ScheduleBatchApexClassExampleScheduler', '0 0 * * * ?', new ScheduleBatchApexClassExample());

Good job, we are done. 

If you want to see your batch job scheduled then 

  • Go to Setup—>Monitor –> Scheduled Jobs

If you want to Schedule a Class in Every 5 Mins in Salesforce, since this is not possible to do through standard Salesforce User interface.


Yes I have solution for it. Small code to do so for every 5 minutes.