+ Start a Discussion
Linda 98Linda 98 

Schedule apex class for roll up calculation

I have an apex class and apex trigger which calculates rollup fields.(6 fields) and updates total fields on the custom object from account object.

Everything works fine but now I want to move this to scheduler class as accounts update doesn't take place from UI and it only updates with a daily run.
So we are trying to write a scheduler class. Below is my apex class and trigger which works fine but when I try to move it to scheduler class and schedule it i am getting an error saying the list has no rows.

I don't want to trigger this class but schedule it to run every day 10 PM EST as my account update runs at 9 PM EST.
Public class rollupclass {
    Public static void totalRollup(List<Account> Acctlist){
        set<id> oppIds = new set<id>();
       
        double totalamt = 0;
       
        try {
                for (Account objacc : acclist){
                    oppIds.add(objacc.Values__c);  //Lookup relationship
               } 

          values__c objval = [SELECT Id,amttotal__c FROM values__c WHERE Id = :oppIds];
 
          List<Account> listAcc = [SELECT Id, amt1__c FROM Account WHERE values__c =:objacc.Id];
                
           for(Account Accounttotals : listAcc) {
                        totalamt += Accounttotals.amt1__c ;
                 }
               
                 objval.amttotal__c = totalamt;
                  update objval;   
            } 
        catch (Exception e) {
            }
    }
 }


 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Linda,

Greetings to you!

You can use below CRON to schedule batch class to run every day at 10 PM.
 
0 0 22 * * ? *

Please refer to below link to generate CRON:

http://www.cronmaker.com/

Also, please refer to below link for more information on Apex Scheduler.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas