Monday 1 August 2011

Apex Scheduler

Apex Scheduler
To invoke Apex classes to run at specific times we use Apex Scheduler
Steps to implement Schedulable Apex
1.       Implement Schedulable Interface for the class

E.g.:        global class scheduledMerge implements Schedulable{
// Schedulable Class 
                                                //Schedulable Method Mandatory for each Interface
global void execute(SchedulableContext SC) {
//Class which has to be scheduled
mergeNumbers M = new mergeNumbers();
}
}
The Schedulable interface contains one method that must be implemented, execute.
global void execute(SchedulableContext sc){}
SchedulableContext object is used to keep track of the scheduled job once it's scheduled.
The SchedulableContext method getTriggerId returns the Id of the CronTrigger object associated with this scheduled job as a string. Use this method to track the progress of the scheduled job.
2.      To Implement the above class in step 1 we need to use System.Schedule Method
The following example uses the System.Schedule method to implement the above class.

scheduledMerge m = new scheduledMerge();// Creating object of the Schedulable
                                                                                                Class
String sch = '20 30 8 10 2 ?';// Format of when and at what time the process is
                                                                scheduled

system.schedule('Merge Job', sch, m); // Implementing the Schedule Process

The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run, and the name of the class. This expression has the following syntax:
Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
The following are the valid values for the above expression:
Name               Values                          Special Characters
Seconds               0–59                             None
Minutes                 0–59                            None
Hours                    0–23                            , - * /
Day_of_month    1–31                              ,- * ? / L W
Month                    1–12 or the following:    , - * /
 JAN – DEC Any Month

Day_of_week      1–7 or the following:      , - * ? / L #
SUN-SAT Any Day

optional_year      null or 1970–2099              , - * /

The special characters are defined as follows:
• , —Delimits values. For example, use JAN, MAR, APR to specify more than one month.
• - —Specifies a range. For example, use JAN-MAR to specify more than one month.
• * —Specifies all values. For example, if Month is specified as *, the job is scheduled for every
month.
• ? —Specifies no specific value. This is only available for Day_of_month and Day_of_week, and
                is generally used when specifying a value for one and not the other.
• / —Specifies increments. The number before the slash specifies when the intervals should
                begin, and the number after the slash is the interval amount. For example, if you specify
                1/5 for Day_of_month, the Apex class runs every fifth day of the month, starting on the
                first of the month.
• L —Specifies the end of a range (last). This is only available for Day_of_month and
                Day_of_week.When used withDay of month, L always means the last day of the month,
                such as January 31, February 28 for leap years, and so on.When used with Day_of_week
                by itself, it always means 7 or SAT.When used with a Day_of_week value, it means the
                last of that type of day in the month. For example, if you specify 2L, you are specifying
                the last Monday of the month. Do not use a range of values with L as the results may be
                unexpected.
• W —Specifies the nearest weekday (Monday-Friday) of the given day. This is only available for
                Day_of_month. For example, if you specify 20W, and the 20th is a Saturday, the class
                runs on the 19th. If you specify 1W, and the first is aSaturday, the class does not run in
                the previous month, but on the third, which is the following Monday.
• # —Specifies the nth day of the month, in the format weekday#day_of_month. This is only
                available for Day_of_week. The number before the # specifies weekday (SUN-SAT). The
                number after the # specifies the day of the month. Forexample, specifying 2#2 means the
                class runs on the second Monday of every month.
The following are some examples of how to use the expression.
Expression Description
0 0 13 * * ?                          Class runs every day at 1 P.M.
0 0 22 ? * 6L                        Class runs the last Friday of every month at 10 P.M.
0 0 10 ? * MON-FRI          Class runs Monday through Friday at 10 A.M.
0 0 20 * * ? 2010                Class runs every day at 8 P.M. during the year 2010.
3.       Create a Test class and Check if it is working properly or not
4.       To check whether the job is Scheduled or not GOTO SetupàAdministration Setup à Monitoring àScheduled Jobs
You can find all the Scheduled jobs here and there start and next run details.
//For Reference check salesforce_apex_language_reference_18.0.pdf – Apex Scheduler

Anonymous Block
An anonymous block is an Apex script that does not get stored in the metadata, but that can be compiled and executed.
Compilation and Execution can be done using the Following:
1.       System Log console
2.       Force.com IDE
3.       The executeAnonymous Force.comWeb Services API call:
ExecuteAnonymousResult executeAnonymous(String code)

Note the following about the content of an anonymous block (for executeAnonymous, the code String):
• Can include user-defined methods and exceptions.
• User-defined methods cannot include the keyword static.
• You do not have to manually commit any database changes.
• If your Apex script completes successfully, any database changes are automatically committed. If your
   Apex script does not complete successfully, any changes made to the database are rolled back.
• Unlike classes and triggers, anonymous blocks execute as the current user and can fail to compile if the
   script violates the user's object- and field-level permissions.
• Do not have a scope other than local. For example, though it is legal to use the global access modifier,
    it has no meaning. The scope of the method is limited to the anonymous block.
executeanonymous() : Executes a block of Apex

Syntax:
ExecuteAnonymousResult[] = binding.executeanonymous(string apexcode);

The executeanonymous() call returns information about whether or not the compile and run of the code was successful.

The ExcuteAnonymousResult has the properties which tells us that if there is a compilation error then at which column number, line and what type of exception has occurred. If Success then it results true.

Implementation Details in Force.Com IDE:
1.       Create a webservice class which has to be executed anonymously.


Example:
global class LocationSample{ 
    webService static boolean getLocation(string strLocation){
    boolean oppExistInCw = false;
   
    //query Location__c Custom Object to search for related Address
         Location__c loc=[Select Name, city__c, country__c,
         Street_Address__c from Location__c where Name=:strLocation];
     if(loc!=null) {
        //update Postal Field
        loc.Postal_Code__c = '500036';
        update loc;
        oppExistInCw = true;
        return oppExistInCw;
     }else{
        return oppExistInCw;
     }   
    }
}
2.       Once Webservice class has been created then goto ExecuteAnonymous block

3.       Once it is successful then the changes will be committed as per your code.

No comments:

Post a Comment

How to include a screen flow in a Lightning Web Component

 Hi, Assume  you have a flow called "Quick Contact Creation" and API Name for the same is "Quick_Contact_Creation". To i...