Thanks to another user (sfdcfox) I've got the following queueable apex being invoked via a screen flow that's being used to update account records. It's taking two string variables from the flow and then passing them into the queueable class to change the owner of Accounts. Being someone that's new to development I'm now starting to learn about Batch vs Queueable apex. Would I be better off using Batch apex for this instead? The goal is to mass update account owner based on the two parameters being passed in via the flow. I'm having trouble understanding if I'd want to use Batch vs Queueable apex for this (thousands of records are being updated). If Batch apex would in fact be the way to go, is there an easy way to convert this code? Not sure if it matters in my decision for using either one of the two but ultimately I'm going to wind up adding related objects to this so that when account owner changes, the opportunity and contact records are updated as well. Here's what I've got so far (that's working for accounts):
Class 1 that includes two string variables being set via the screen flow:
public class TerritoryAssignmentVariables {
@InvocableVariable
public String oldOwnerId;
@InvocableVariable
public String newOwnerId;
Class 2 for the Queueable apex that's accepting the variables from Class 1:
public class TerritoryAssignmentClass implements Queueable {
@InvocableMethod(label = 'Update Records')
public static void updateAccounts(List<TerritoryAssignmentVariables> IDValues){
List<Account> Updatedaccounts = new List<Account>();
for(TerritoryAssignmentVariables value : IDValues){
for(Account acc : [SELECT Id, Owner.Id FROM Account WHERE Owner.Id = :value.oldOwnerId]){
acc.OwnerId = value.newOwnerId;
Updatedaccounts.add(acc);
}
}
System.enqueueJob(new TerritoryAssignmentClass(Updatedaccounts));
}
// State to update records //
Account[] scope;
TerritoryAssignmentClass(Account[] scope) {
this.scope = scope;
}
// Queueable Context execution //
public void execute(QueueableContext ctx) {
Account[] accountsToUpdate = new Account[0];
// Adjust 100 as needed //
while(accountsToUpdate.size()<100 && !scope.isEmpty()) {
accountsToUpdate.add(scope.remove(0));
}
update accountsToUpdate;
// We have more work to do, so enqueue again //
if(!scope.isEmpty()) {
System.enqueueJob(this);
}
}
Thanks for any guidance you can provide.