-2

I know, it should not be done. But theoretically is it possible?

Gargi Gupta
  • 151
  • 2
  • 14
  • 2
    Directly, in a word: no. You need to run the same processing not in a batch but then you need to ensure that you only process as much (as many records) as you can fit into the lower synchronous governor limits. I.e. you can, but you cannot process as much data. – Phil W Aug 14 '22 at 18:17
  • 4
    What specifically are you trying to accomplish? This seems like one way to solve a problem you have thought of, but not the actual problem itself. See also: XY Problem. – Adrian Larson Aug 14 '22 at 18:45

1 Answers1

2

Batchable logic are just normal methods. You can emulate Database.executeBatch using something like this:

public static void executeBatchSync(Database.Batchable<Object> batch, Type iterableType, Integer batchSize) {
    Iterable<Object> iterableObject = batch.start(null);
    Iterator<Object> iter = iterableObject.iterator();
    Object[] temp = (Object[])iterableType.newInstance();
    Integer size = 0;
    while(iter.hasNext()) {
        temp.add(iter.next());
        size++;
        if(size == batchSize) {
            batch.execute(null, temp);
            temp.clear();
            size = 0;
        }
    }
    if(!temp.isEmpty()) {
    batch.execute(null, temp);
    }
    batch.finish(null);
}

Which would be called using something like this:

Utils.executeBatchSync(new MyBatchable(), List<Account>.class, 200);

Note that you'll be subject to normal synchronous limits, but you'd be able to use the class directly. It would probably be better to have your Batchable class call a utility class/method, though, so you don't need to emulate the entire Batchable runtime.

Edit: Please note that there are some major issues with types, so you might have to fiddle with this code to make it run properly with certain data types, or possibly implement multiple variants based on the expected return type of the start method. As I stated above, it's better to have a utility class you can call directly from both the batch and wherever you want to run this logic (for example, a trigger), rather than try to implement this. This answer is mostly an answer to an academic question, rather than something you should implement in production.

sfdcfox
  • 489,769
  • 21
  • 458
  • 806