You need to sign in to do that
Don't have an account?
Vianney Bancillon 8
Implement Schedulable interface and Database.Batchable interface in a single class
Hi everyone!
I read in a previous post that it is possible to implement both in a single class, but the post didn't give any exemples.
Could you explain how to do that to me (with exemples if possible)
Thanks!
Vianney Bancillon
I read in a previous post that it is possible to implement both in a single class, but the post didn't give any exemples.
Could you explain how to do that to me (with exemples if possible)
Thanks!
Vianney Bancillon
All Answers
Thanks Saurabh...
Same class can implement both interface Database.Batchable and Schedulable. These two names have to be comma-separated after the "implements" keyword in the class defition. In the below code "Check_x_min_trigger__c" is a custom field of type text on Account. The batch class queries for all accounts and assigns the value "Same class implements both interfaces" to this custom field on all the account records. The "execute" method given in the end (which takes parameter SchedulableContext) is called to schedule the Apex Scheduler from Developer Console using this code :-
DoubleImplement doubleImplementObj = new DoubleImplement();
String timeScheduleString = '0 20 * * * ?'; // Apex Scheduler will run 20 minutes past every hour
String schedulerJobID = system.schedule('Scheduler Name String', timeScheduleString, doubleImplementObj);
Open the "Open Execute Anonymous Window" of Developer Console from this path (to run the above three lines of code) :-
Setup -> Developer Console -> Debug -> Open Execute Anonymous Window
See the scheduled apex job at this path :-
Setup -> Monitor -> Jobs -> Scheduled Jobs
*/
global class DoubleImplement implements Database.Batchable<SObject>, Schedulable
{
global Database.QueryLocator start(Database.BatchableContext bc)
{
String query = 'Select id, name, City__c, Check_x_min_trigger__c from Account';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, list<SObject> scope)
{
System.debug(LoggingLevel.INFO, '#### execute method of batch class starts');
List<Account> accLstToUpdate = new List<Account>();
if(scope != null)
{
List<Account> accLst = (List<Account>)scope; // typecast List<SObject> to List<Account>
for(Account a : accLst)
{
a.Check_x_min_trigger__c = 'Same class implements both interfaces';
accLstToUpdate.add(a);
}
if(accLstToUpdate.size() > 0)
{
System.debug(LoggingLevel.INFO, '#### execute method of batch class: updating accLstToUpdate ' + accLstToUpdate.size());
update accLstToUpdate;
}
}
}
global void finish(Database.BatchableContext BC)
{
System.debug(LoggingLevel.INFO, '#### finish method of batch class');
}
global void execute(SchedulableContext sc)
{
System.debug(LoggingLevel.INFO, '#### execute method of scheduler starts');
DoubleImplement di = new DoubleImplement();
Database.executeBatch(di);
}
}