+ Start a Discussion
Sfdc SivaSfdc Siva 

Need help to creating scheduled apex class

Hi All,

I have created onebatch apex as mentioend below.I want to scheduled the class everday midnight automatically.Can any one help me to create a Automatic scheduled class.

BatchApex:
global class OpportunitySplit implements Database.Batchable<Sobject>{
    global OpportunitySplit(){
    }
        //START Method
        global Database.QueryLocator start(Database.BatchableContext BC){
        DateTime dt = DateTime.now().addHours(-24);
        String query = 'SELECT Id,name,Total_Account_Manager__c,Total_Channel_Manager__c FROM Opportunity WHERE LastModifiedDate = ToDay ';
        return Database.getQueryLocator(query);
        }
        //execute Method
        global void execute(Database.BatchableContext BC,List<Opportunity> lstOpp){

            Map<Id,Integer> MapIdOppTosumAcMngr = new Map<Id,Integer>();
            Map<Id,Integer> MapIdOppTosumChMgnr = new Map<Id,Integer>();
            Map<Id,Opportunity> MapOpportunity = new Map<Id,Opportunity>(lstOpp);
            Opportunity objOppToUpdate;
            
            List<Opportunity> lstOppToUpdate = new List<Opportunity>();           
            for(OpportunitySplit objOppSplit : [SELECT Id, Role_Name__c, OpportunityId FROM OpportunitySplit WHERE Role_Name__c IN (' Account Manager',' Channel Manager') AND OpportunityId IN: MapOpportunity.keySet()]){                                     
                system.debug('====objOppSplit===='+objOppSplit);
                
                if(objOppSplit.Role_Name__c == 'Account Manager'){
                   
                    MapIdOppTosumAcMngr.put(objOppSplit.OpportunityId, MapIdOppTosumAcMngr.containsKey(objOppSplit.OpportunityId) ? (MapIdOppTosumAcMngr.get(objOppSplit.OpportunityId)+1): 1);
                }
                else{
                      
                     MapIdOppTosumChMgnr.put(objOppSplit.OpportunityId,MapIdOppTosumChMgnr.containsKey(objOppSplit.OpportunityId) ? (MapIdOppTosumChMgnr.get(objOppSplit.OpportunityId)+1): 1);
                    }
            }
            for(Opportunity objOpp : MapOpportunity.values()){
                objOppToUpdate = new Opportunity(Id = objOpp.Id);
                objOppToUpdate .Total_Account_Manager__c = MapIdOppTosumAcMngr.containsKey(objOpp.Id) ? MapIdOppTosumAcMngr.get(objOpp.Id) : 0;
                objOppToUpdate .Total_Channel_Manager__c = MapIdOppTosumChMgnr.containsKey(objOpp.Id) ? MapIdOppTosumChMgnr.get(objOpp.Id) : 0;
                
                lstOppToUpdate.add(objOppToUpdate );
            
                system.debug('====objOppToUpdate===='+objOppToUpdate);
            }
                if(!lstOppToUpdate.isEmpty())
                    
                    update lstOppToUpdate;         
        }
         //finish Method
                global void finish(Database.BatchableContext BC){
                    
                }
}

Thanks in Advance
Lalit Mistry 21Lalit Mistry 21
Hi Siva,

Create a scheduler class as below
global class OppSplitScheduler implements Schedulable {
   global void execute(SchedulableContext SC) {
      OpportunitySplit oppSplit = new OpportunitySplit();
	  Database.executeBatch(oppSplit, 1000);
   }
}

After creating this class, go to Setup -> Develope -> Apex Classes and click 'Schedule Apex' button to schedule the above created class.
Hope this helps.
Nagendra Prasad ChNagendra Prasad Ch
Hi Siva,

Here is the schedule class for the apex batch,
global class scheduledOpportunitySplit implements Schedulable{
   global void execute(SchedulableContext SC) {
		   OpportunitySplit oppSplit = new OpportunitySplit ();
           Database.executeBatch(oppSplit); 
   }    
}

You need to either use Saleforce UI or run code in anonymous window to schedule this class.
1) To schedule it from UI, follow below procedure, select scheduledOpportunitySplit ​ class.
https://help.salesforce.com/articleView?id=code_schedule_batch_apex.htm&language=en_US&type=0

2) To schedule it through developer console paste below code in anonymous winondow of developer console and run the code.
It runs job everyday 6 AM.

scheduledOpportunitySplit bd = new scheduledOpportunitySplit ();
        String cronStr = '0 0 6 * * ?';
        system.schedule('scheduledOpportunitySplit Job', cronStr, bd);


Refer below links for more info,
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm
Ajay K DubediAjay K Dubedi
Hi Sfdc Siva,

Here, you created a Batchable Class and now, you need to Follow some Steps:

(1) Create a Schedule class that implements Schedulable Interface.
(2) In schedule class, you need to write execute method of Schedulable Interface.
(3) In execute Method, create batchable class Instance and pass this Instance inside the Database.executeBatch( .. ) Method.
(4) now, open Execute Anonymous Window in developer console and press ctrl + E. Here, one window is open.
(5) Create a Schedule class Instance and call a System.schedule(.....) method.
(6) In System.schedule method, there are three parameters. In First parameter, pass the name of schedule you want to create. In Second Parameter, pass a corn String that implements your logic to start batch in every mid-night. 
 In Last or Third parameter, you need to pass your schedule class instance.
(7) And press Execute Button. 

Schedule Class
global class ScheduleOpportunitySplit implements Schedulable {
    
    global void execute(SchedulableContext sc){
        OpportunitySplit myOpportunitySplit = new OpportunitySplit();
  Database.executeBatch(myOpportunitySplit);
    }

}
Create a schedule
ScheduleOpportunitySplit sost = new ScheduleOpportunitySplit();
String jobID = System.schedule('Schedule on Opportunity', '0 0 0 * * ?', sost);
Regards,
Ajay
 
Sfdc SivaSfdc Siva
Hi Nagendra Prasad,
Thanks for your quick response.I have one quey.
1.If i schedule it from UI (Weekly) can i select Monday to friday? 
2.How the database will understood whether scheduleapex is  schedued everday midnight? 
3.In below scheduled class i havn't mentioend any midnight(proper)time.
4.We want to run the schedueld apex automatically run everday midnight. Where we can confugured the proper time? 

global class scheduledOpportunitySplit implements Schedulable{
    global void execute(SchedulableContext SC){
        OpportunitySplit  oppSplit = new OpportunitySplit();
        Database.executeBatch(oppSplit);
    }    
}

Can you please check below code and correct me.

Thanks
Siva
Sfdc SivaSfdc Siva
Hi Ajay,
 
Still i have bit of confusing. Hear I have created a scheduled class as mentioned below. And i have scheduled the class like Recurse every weekly. After that i have mentioned preferred time every day midnight 1AM and saved the Schedule Apex.
 
Now my question is below class i did not mentioned any scheduled time like this (String job ID = System. Schedule ('Schedule on Opportunity', '0 0 0 * *?', sost)).Is that mandatory to mentioning '0 0 0 * * ?'Time in the class or anywhere else we need to use? or else preferred time is enough? Please confirm.
 
And i have one quick question Can you please explain this "'0 0 0 * *?'".
 
Scheduled apex class:
global class scheduledOpportunitySplit implements Schedulable{
    global void execute(SchedulableContext SC){
        OpportunitySplit  oppSplit = new OpportunitySplit();
        Database.executeBatch(oppSplit);
    }   
}
 
Thanks,
Siva
 
Nagendra Prasad ChNagendra Prasad Ch
If u want schedule batch at 1 AM every day, run this code in Execute Anonymous Window in developer console( presee Ctrl + E from Developer console).
 
ScheduleOpportunitySplit sost = new ScheduleOpportunitySplit();
String jobID = System.schedule('Opportunity split job', '0 0 1 * * ?', sost);
0 0 1 * * ? is called cron expression which  tells system the time to run the job.
It is in the form of  Seconds  Minutes  Hours  Day_of_month  Month Day_of_week  Optional_year

 Refer below links for more info on cron expressions,
https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm

http://docs.embarcadero.com/products/er_studio_portal/erstudioPortal2.0/HTMLHelp/Admin/erstudioportal/erstudioportaladministratorsguide/cron_expression_examplescron_expression_examplecreates_trigger.htm