Tuesday, November 20, 2018

Asynchronous Apex: Scheduled Apex in Salesforce.com

Scheduled Apex 

Scheduled Apex lets you run Apex classes at a specified time; for example, This is ideal for daily or weekly maintenance tasks using Batch Apex. 

To invoke Apex classes at specific times, first implement the Schedulable interface for the class. Then, schedule an instance of the class to run at a specific time using the System.schedule method.

Note: Governor limits in case of asynchronous are higher as compared to synchronous. 

Schedule Apex Syntax:

global class SomeClass implements Schedulable {
    global void execute(SchedulableContext cntx) {
        // awesome code here
    }
}

Schedulable Apex

global class RemindOpptyOwners implements Schedulable {

    global void execute(SchedulableContext cntx) {
        List<Opportunity> opptys = [Select Id, Name, OwnerId, CloseDate  From Opportunity  Where IsClosed = False AND CloseDate < TODAY];
        
// Call util class and method here to create a task for each opportunity in the list
        TaskUtils.remindOwners(opptys);
    }
    
}

System.Schedule Method

It takes three arguments: 
1) Job name

2) CRON expression used to represent the time and date the job is scheduled to run

3) Instance variable of the class object

//Create a instance variable of the class object
RemindOpptyOwners reminder = new RemindOpptyOwners();

//Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
String sch = '20 30 8 10 2 ?';

String jobID = System.schedule('Remind Opp Owners', sch, reminder);

Sec Min Hours Days Month WeekDay  Years 

0 0,30      * * * ? *

0 5 20 ? Jan,May Mon-Fri 2017

* --> All Values
? --> No Values


Monitoring Scheduled Jobs

It uses a job_Id variable which is returned from the System.schedule method.

CronTrigger ct = [Select TimesTriggered, NextFireTime From CronTrigger Where Id= :jobID];

Monitoring Queued Jobs

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

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

Schedule Apex Consideration:
1) You can only have 100 scheduled Apex jobs at one time, and the maximum number of scheduled Apex executions per a 24-hour period. 

2) Synchronous Web service callouts are not supported from scheduled Apex. But we can 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.)












No comments:

Post a Comment

Validation in flow input text field in sfdc: Maximum 255 characters limit

The input text field validate in sfdc flow behaves opposite of the generic sfdc validation rule.  Here the validation formula is evaluating ...