Salesforce Asked on November 15, 2021
I have the following code that adds the execute batch into a list.
List<String> batches = new List<String>();
batches.add(Database.executeBatch(batch1, batchSize));
What I want to do is to be able to pop off the batch from the list and execute it:
Database.executeBatch(batches[0]);
Unfortunately, this does not work though. I receive the below error.
Method does not exist or incorrect signature: void executeBatch(String) from the type Database
You've got it wrong. You need to add the batchables to a list to execute, then pop off those values and execute them later. The instant you call Database.executeBatch, it queues that batch, and the return value is just the Job Id. That said, there's a better way to do this. You can create a chainable job design. One such design looks like this:
public class Batch implements Database.Batchable<Object>, Database.Stateful {
public interface Job {
Object start(Database.BatchableContext context);
void execute(Database.BatchableContext context, Object[] scope);
void finish(Database.BatchableContext context);
Integer batchSize();
}
Job[] jobs = new Job[0];
Job currentJob;
public void addJob(Job newJob) {
jobs.add(newJob);
}
public void execute() {
if(!jobs.isEmpty()) {
currentJob = jobs.remove(0);
Database.executeBatch(this, currentJob.batchSize());
}
}
public Iterable<Object> start(Database.BatchableContext context) {
return (Iterable<Object>)currentJob.start(context);
}
public void execute(Database.BatchableContext context, Object[] scope) {
currentJob.execute(context, scope);
}
public void finish(Database.BatchableContext context) {
currentJob.finish(context);
execute();
}
}
Each job might look something like this:
public class Job1 implements Batch.Job {
String query;
public Job1(String queryString) {
query = queryString;
}
public Object start(Database.BatchableContext context) {
return Database.getQueryLocator(query);
// Can also be a list of anything else, too //
}
public void execute(Database.BatchableContext context, Object[] scope) {
// Do stuff with scope //
}
public void finish(Database.BatchableContext context) {
// Finish up //
}
public Integer batchSize() {
return 200;
}
}
Now, you can build a chain of jobs:
Batch jobs = new Batch();
jobs.add(new Job1(...));
jobs.add(new Job2(...));
jobs.add(new Job3(...));
jobs.execute();
They will process in order automatically. You can even store extra data in, say, Job1 to have it execute based on parameters.
Answered by sfdcfox on November 15, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP