Schedule Apex Code #inSalesforce

Schedule Apex Code #inSalesforce

To invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the schedule using either the Schedule Apex page in the Salesforce user interface or the System.schedule method.


Suppose we want to schedule this class:

global class batchJobAccounts implements Database.Batchable<sObject>{
    global Database.QueryLocator start(Database.BatchableContext bc){
        String query = 'SELECT Id, Active__c, Description FROM Account';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext bc, List<Account> scope){
        for(Account act: scope){
            act.Active__c = True;
            act.Description = 'Activated';
        }
        update scope;
    }
    global void finish(Database.BatchableContext bc){
        system.debug('!!!!Job Completed!!!!!');
    }
}


The Class:

global class scheduleApexExample implements Schedulable{    
    global void execute(SchedulableContext sc){
        batchJobAccounts batchJob = new batchJobAccounts();
        Database.executeBatch(batchJob,200);
        
    }
}


Try in Anonymous Window:

scheduleApexExample theScheduler = new scheduleApexExample();
String theSchedule = '0 0 9 * * ?';
System.schedule('!!!activatedAccount!!!', theSchedule,theScheduler);


To view the status: Setup | Scheduled Jobs

Reference:

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

Comments