Schedulable Apex | Salesforce

SCHEDULABLE APEX IN SALESFORCE

Till the last Episode, we discuss about what is the batch apex as well as how to write batch apex in salesforce. I hope now you are able to write batch apex in salesforce. 

In this episode, we are going to learn about how to write schedulable batch apex in salesforce.
Let's get started Kid.....

APEX SCHEDULAR : 
Now, what actually apex scheduler does right ?? 

It invokes the Apex class to run at a specific time. Anybody who want to schedule their class they have to implement the schedulable interface.

SCHEDULABLE INTERFACE :
The class that implements this interface can be scheduled to run at different intervals. This interface has several methods like
================================
public void execute(SchedulableContext SC)    
================================

FOR EXAMPLE :
===========================================
public class MySchedule implements schedulable
{
 public void execute(SchedulableContext SC)
 {
  Account a = new Account(Name='Ajinkya');
 insert a;
 }
}
===========================================

The scheduler will run in SystemContext, Which means all the classes are executed whether the user has permission or not.

We can monitor or stop the execution of scheduled apex job using salesforce user interface from setup.

NAVIGATION :

SETUP -> MONITORING -> JOBS -> SCHEDULED JOBS

The execute() method must be declared as public or global using system.schedule

SYSTEM.SCHEDULE :
Once you are implemented schedulable interface use system.schedulable method to execute the class.

system.schedule() method takes 3 parameters :
1. Name of the job
2. An expression that is used to represent the time and date of the operation.
3. The object of the class which you want to execute.

An expression is written in the form of 'Seconds, minutes, hours, day of the month, month day of the week, optional year.'

'Seconds' : 0-60
'Min' : 0-60
'Hours' : 0-24
'Day-Months' : 1-31
'Month' : 1-12
'Day-Week' : 1-7
'Optional Year' : --

SPECIAL CHARACTERS :

?Special character specifies no specific value. This is only available for the day of the month and day of the week.

EXAMPLE 1 :
Write the expression to schedule an operation 10th of August at 12:30 PM.
===========================================
'0 30 12 10 8 ?'
'0 30 12 10 AUG ?'
'0 30 12 10 AUG ? 2013'
===========================================

EXAMPLE 2 :
Write an expression to schedule an operation on Jan Monday 12:30.
===========================================
'0 30 12 ? 1 MON'
'0 30 12 ? 1 2'
===========================================
* : Specifies all the values 

EXAMPLE 1 :
Write the expression to schedule an operation on every day of the AUG at 12:30 PM.
===========================================
'0 30 12 * AUG ?'
'0 30 12 * 8 ?'
===========================================

EXAMPLE 2 :
Expression to schedule on every hour on 10th AUG.
===========================================
'0 30 * 10 8 ?'
===========================================

L : Specifies the end of the range. This is available the only day of the month or day of the week.

EXAMPLE :
Write an expression to schedule the operation on last Friday of March at 10:20.
===========================================
'0 20 10 ? 3 6L'
===========================================

W : Specifies nearest weekday of the given day this is available for the only day of the month.

EXAMPLE :
If we specifies 20W and 20th is a Saturday so the class runs on 19th. If I give 1W and 1st is a Saturday then it runs on Monday, not on the previous month.

EXAMPLE :
Write an expression to schedule an operation on the nearest weekday of March 20th at 10:20.
===========================================
'0 20 10 20W 3 6L'
===========================================

This is to specify the last working day of last weekday of last the month.

# : This specifies the N'th day of the Month.

EXAMPLE :
===========================================
Week_Day # Day_Month
2 # 2 //It will run monday of every 2nd month
===========================================

) : JAN, MAR means JAN-MAR.

If you want to schedule any operation we have to create an object for the class which has implemented for Schedulable Interface.

FOR EXAMPLE :
===========================================
class MySchedule implements Schedulable  
{
 public void execute(SchedulableContext BC)
 {
  //---------//
 }
 MySchedule mysc = New MySchedule();
 String str = '0 0 10 * 3 2';
System.schedule('MyJob', str, mysc); // MyJob is Name, str is Time Format, mysc is Object
}
===========================================

System.schedulableBatch() :

System.scheduleBatch() is used to run a schedule a batch job only once for a future time. This method has got 3 parameters. 

param 1 : Instance of a class that implements Database.Batchable interface.
param 2 : Job name.
param 3 : Time interval after which the job should start executing.
param 4 : It's an optional parameter which will define the no. of that processed at a time. The system.scheduleBatch() returns the scheduled job Id.
We can use the job Id to abort the job.

EXAMPLE :
You have to first implement the schedulable interface for the class the specify the schedule using schedule Apex page or system.schedule method.
===========================================
global class purge implements schedulable 
{
 global void execute(SchedulableContext SC)
 {
  List<credit_card__c> creditcard = new List<credit_card__c>();

  for(credit_card__c cc : [SELECT Id, Name FROM credit_card__c WHERE Age__c > 2])
 {
  creditcard.add(cc);
  cc.cw__c = '0000';
  }
   Database.update(creditcard);
  }
}
===========================================

QUESTION IS HOW TO SCHEDULE ? CORRECT ??

If we want to schedule

STEP 1 : 
Create an object for the class which has implemented the schedulable interface.

STEP 2 :
Create the time frame.

STEP 3 :
Invoke the system.schedule method with job name, schedule object, timeframe.

So let's create something by following above STEPS....GO GO GO Kid ☁️⚡️

FOR STEP 1 :
===========================================
global class MyBatch implements Database.Batchable <sObject>
{
 global Database.QueryLocator Start (Database.BatchableContext bc)
 {
  return Database.getQueryLocator('SELECT Id, Name FROM Account'); 
 }
 global void execute(Database.BatchableContext BC, List<sObject> scope)
 {
  List<Account> acc = new List<Account>();
  for(sObject x : scope)
  {
   Account a = (Account)x;
   a.name = 'Mr' + a.name;
   acc.add(a);
  }
 update acc;
 }
 global void finish(Database.BatchableContext bc)
 {

  }
}   
==========================================

FOR STEP 2 :
==========================================
global class MySchedule implements schedulable
{
 global void execute(SchedulableContext sc)
 {
 MyBatch mb = new MyBatch();
 Database.execute(mb);
  }
}
==========================================

FOR STEP 3 :
==========================================
global class TestSchedule
{
 public pageReference show()
{
  String timeframe = '0 10 8 10 * ?';
  MySchedule ms = new MySchedule();
  System.schedule('MyMob', timeframe, ms);
 }
} 
=========================================

Now create a visualforce page to test this.

VISUALFORCE PAGE :
=========================================
<apex:page Controller='TestSchedule'>
 <apex:form>
  <apex:commandButton value="click" action="{!show}"/>
 </apex:form>
</apex:page>
=========================================

In this way, we can easily use schedulable apex in salesforce. But there are some limitations of the schedulable apex as well which we always have to consider.

SCHEDULE APEX LIMITATIONS :
=========================================
1. We can schedule only 100 jobs at a time.
2. Max no. of apex schedule jobs in 24 hours is 2,50,000 number of jobs (can change with salesforce updates).
3. Synchronous WebService callouts are not supported in schedulable Apex.
=========================================

These are limitations of schedule apex in salesforce. This is quite easy to implement the only thing is to follow the proper steps and that's it 😊 you are good to go now.

In the upcoming episode, we will talk about apex sharing rules and then we will start learning how to write the salesforce Test classes.


WOHOOO !! YOU HAVE JUST COMPLETED SALESFORCE SCHEDULABLE APEX EPISODE
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you 
Happy learning ☁️⚡️ (Learn. Help. Share.)

<< PREVIOUS                                      NEXT >>

Schedulable Apex | Salesforce Schedulable Apex | Salesforce Reviewed by on Rating: 5

1 comment:

  1. Good Post. I like your blog. Thanks for Sharing
    Digitally sign your documents instead of doing it manually with the help of DocuSign Integration with Salesforce using API's

    ReplyDelete

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.