At first we should write a Batch class without a schedule code in it.
create the below schedule class.
Schedule Class
global class ScheduleClass implements Schedulable {
global void execute(SchedulableContext sc) {
BatchClass b = new BatchClass();
database.executebatch(b);
}
}
After saving that schedule class append the code which I have highlighted in red color in finish method of batch Apex.
Batch Class
global class BatchClass implements Database.Batchable<sobject>
{
global Database.QueryLocator start(Database.BatchableContext BC){
String Query='Select LastName,Id from Lead';
return Database.getQueryLocator(Query);
}
global void Execute(Database.BatchableContext BC,List<sobject> Scope){
List<Lead> ld = Scope;
for(Lead l: ld){
l.LastName = l.LastName+'Batch testing';
}
}
global void finish(Database.BatchableContext BC){
Datetime sysTime = System.now();
sysTime = sysTime.addMinutes(60);
String chron_exp = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' +
sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();
system.debug(chron_exp);
ScheduleClass ssr = new ScheduleClass(); // Schedule class name
String sch = 'Schedulejob' + chron_exp;
List<AsyncApexJob> aaj = [select ApexClassID,CompletedDate,ExtendedStatus,
JobItemsProcessed,JobType,MethodName,
NumberOfErrors,Status,TotalJobItems
from AsyncApexJob
where status='queued'];
if(aaj.size()== 0){
system.schedule(sch,chron_exp,ssr);
}
}
}
The chron_exp will used to schedule the class for every 1 hour based on the System Time.
we need to execute the above code as a anonymous using developer console.
Once it has been started to execute, it will automatically schedule the apex class for every 1 hour.
No comments:
Post a Comment