I have an invocable that I plan to use that can help let a flow user choose to execute a process only every other week based on their inputs of "Current Day of the Week" (string), and a Start Date.
So if someone were to input 'Monday' and choose a start date of 5/1/2024, then the next time the flow element should return true would be when the flow runs on 5/15/2024.
I have 1 method that should get the next occurrence of a specified day of the week:
// Helper method to find the next occurrence of the specified day of the week
@TestVisible
private static Date getNextDayOfWeek(Date fromDate, String dayOfWeek) {
Integer targetDay = getDayOfWeekAsInteger(dayOfWeek);
DateTime dateTimeVar = DateTime.newInstance(fromDate.year(), fromDate.month(), fromDate.day());
Integer currentDay = Integer.valueOf(dateTimeVar.format('u')); // 'u' gives the digit day of the week
Integer daysToAdd = targetDay - currentDay;
if (daysToAdd < 0) {
daysToAdd += 7;
}
return fromDate.addDays(daysToAdd);
}
And another helper method to try and calculate the next run date:
// Helper method to calculate the next run date based on start date and day of the week
public static Date calculateNextRunDate(Date startDate, String dayOfWeek, Date today) {
Date nextDayOfWeek = getNextDayOfWeek(today, dayOfWeek);
// Calculate days between start date and next occurrence of the target day
Integer daysBetween = startDate.daysBetween(nextDayOfWeek);
// Adjust the next run date to ensure it's on a bi-weekly schedule
while (Math.mod(daysBetween, 14) != 0) {
nextDayOfWeek = nextDayOfWeek.addDays(7);
daysBetween = startDate.daysBetween(nextDayOfWeek);
}
return nextDayOfWeek;
}
The problem is using Math.mod in a loop like that causes Apex cpu limits.
Is there an easier approach to this using Apex (or any other method)?
Math.mod()
in a loop, but more that you have an infinite loop. IfdaysBetween
is not a multiple of 7, you'd never get to a multiple of 14 by adding 7. Might be worthwhile to set up a counter and a debug to see just how many times your loop is running.