I would typically set up a batchable context like the code below.
Execute via a schedule like: OpportunityLineItemsRefreshJob.scheduleMe();
To execute from a controller I would do the following:
OpportunityLineItemsRefreshJob batchJob = new OpportunityLineItemsRefreshJob();
ID batchprocessid = Database.executeBatch(batchJob);
// ....
// ....
global with sharing class OpportunityLineItemsRefreshJob implements System.Schedulable, Database.Batchable<SObject>, Database.Stateful
{
// Schedule String
public static String sched = '0 00 00 * * ?'; //Every Day at Midnight
// Method to execute schedule
global static String scheduleMe()
{
OpportunityLineItemsRefreshJob Job = new OpportunityLineItemsRefreshJob();
return System.schedule('Refresh OLIs for Roll Up Summary Fields', sched, Job);
}
global void execute(SchedulableContext sc)
{
// Start the job once the scheduled time has arrived
Database.executeBatch(new OpportunityLineItemsRefreshJob());
}
public Database.QueryLocator start(Database.BatchableContext context)
{
// Obtain appoprite query locator from the selector
return new OpportunityLineItemsSelector().queryLocatorReadyToMassUpdate();
}
public void execute(Database.BatchableContext context, List<OpportunityLineItem> olis)
{
try
{
// OpportunityLineItems ready to Update
Set<Id> olisToUpdate = new Map<Id, SObject>(olis).keySet();
new OpportunityLineItemService().updateOLIMassUpdate(olisToUpdate);
}
catch (Exception e)
{
// Catch
}
}
public void finish(Database.BatchableContext context)
{
}
}