0

can we invoke another class method from batch apex? I need to call EndDateStartDateDifference method (from DaysDifference class) in TimeCalculator batch apex with firstDate value (fetch in query) and finish date value(system.today).

simple class:-

public with sharing class DaysDifference {
    public static integer EndDateStartDateDifference(date firstDate, date finishDate) {
        integer difference= firstDate.daysBetween(finishDate);
        return difference;
    }
}

Batch apex:-

global class TimeCalculator implements Database.Batchable<SObject>{

    global Database.QueryLocator start(Database.BatchableContext context) {
        string getTLRecord = 'SELECT Start_Date__c FROM Time_Log__c';
        return Database.getQueryLocator(getTLRecord);
    }

    global void execute (database.batchableContext context, List<Time_Log__c> scope){
        DaysDifference.EndDateStartDateDifference(??,??);
       
    }

    global void finish(database.batchableContext context){

    }
}
0

1 Answer 1

1

Yes you can, and it's done just like how you would call any other method.

You'll need to loop over the batch's scope to get the start date to pass to your static EndDateStartDateDifference() method. E.g.

for(My_Object__c myRecord :scope){
    // do work
}

You'll also (unsurprisingly) need to provide the end date. Since the end date isn't going to be different from record to record, this is something that you should do outside of (and before) your loop. A simple Date endDate = Date.today(); should do fine.

Be aware that calculating the date difference isn't going to automatically cause your records to be updated. There's not much use in calculating something if you're not going to put that difference into a field or otherwise use it for another purpose. If you're only trying to update your records with this date difference, using a formula field is likely to be the more appropriate solution.

2
  • can you please tell me how to get start date by iterating through scope. and how to put the result in time log object field.
    – Jason
    Apr 20, 2022 at 4:01
  • @Jason By using dot notation to access the field? e.g. myRecord.Start_Date__c. It sounds like you may not know some important fundamentals here. The Apex Basics & Database module on trailhead (and parts of the Apex Basics for Admins module) would be good things to go through (especially if you're not super familiar with writing code).
    – Derek F
    Apr 20, 2022 at 13:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .