0
    global class NumberOfContactsBatch implements Database.Batchable<SObject>, Database.Stateful {

    global Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([select Id from Account order by Name]);
    }

    global void execute(Database.BatchableContext context, List<Account> scope) {
        List<Account> accountUpdate = new List<Account>();
        for (AggregateResult ar : [
                select AccountId a, count(Id) c
                from Contact
                where AccountId in :scope
                group by AccountId
                ]) {
            accountUpdate.add(new Account(
                    Id = (Id) ar.get('a'),
                    Number_of_Contacts__c = (Decimal) ar.get('c')
                    ));
        }
        update accountUpdate;
    }

    global void finish(Database.BatchableContext context) {
    }
    global void execute(SchedulableContext SC){
        database.executeBatch(new NumberOfContactsBatch());
        String cronExpression = '';
        System.schedule(cronExpression);        
    } 
}

I got stuck here where I want write a scheduler which runs every six hours

  • 1
    Your scheduler is already written correctly. Do not put any cron in your class. Use an anonymous script for that. – Adrian Larson Mar 28 '20 at 18:22
  • Actually it is giving me this error "Method does not exist or incorrect signature: void schedule(String) from the type System" I mean after this i only have to execute it like this Database.executeBatch(new NumberOfContactsBatch()); isnt it? – H John Mar 28 '20 at 18:28
  • Remove everything from your scheduler except Database.executeBatch – Adrian Larson Mar 28 '20 at 18:53
  • ok got it. Then I have to write this line NumberOfContactsBatch obj = new NumberOfContactsBatch(); String cron = 'my cron expression'; String jobId = System.schedule('Job', cron, obj); Thanku – H John Mar 28 '20 at 18:56
1

You are trying to Schedule a batch class without a scheduler to Implement SchedulableContext, for this Schedulable Interface should be implemented

For Example:

Class NumberOfContactsSchedulabler implements Schedulable {
     global void execute(SchedulableContext SC) { 
        database.executeBatch(new NumberOfContactsBatch());
    }
}

Run the following Code in anonymous window (One time)

NumberOfContactsSchedulabler m = new NumberOfContactsSchedulabler();
String sch = '0 0 0/6 1/1 * ? *'; //Schedules the job to run every 6 hours
String jobID = system.schedule('Contacts Schedulable', sch, m);

Cron maker help can be found here

Also the Method "global void execute(SchedulableContext SC)" can be removed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.