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
Database.executeBatch