1

I'm not even sure how to ask this question, but here goes:

I have Batch class that needs to maintain state. The class looks something like this:

global class myBatch implements Database.Batchable<sObject>, Database.Stateful {

    global id[] AppliedChanges;

    global database.Querylocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(accountsQuery);
    }

    global void execute(Database.BatchableContext bc, Account[] scope){
        myBatch.doWork(scope);
    }

    global void finish(Database.BatchableContext bc){
        //do something with AppliedChanges
    }

    public static void doWork(){
        AppliedChanges = AppliedChanges == null ? new id[]{} : AppliedChanges;
        //Do tons of work, eventually populate add to AppliedChanges
    }
}

In doWork(), I can debug AppledChanges and see that it has values but, in the finish() method, AppliedChanges is always null.

The doWork() method exists so I can use that logic elsewhere in Salesforce without having to run a batch.

How can I populate AppliedChanges in the doWork() method and then use it in finish()?

1

1 Answer 1

1

You need to remove the static keyword. It basically means "stateless", which is the opposite of what you want.

Works

public void doWork()

Fails

public static void doWork()
1
  • Sigh... I knew it was something like that. I ended up having two change doWork() to doWorkInternal(), then add a new method for doWork() like: public static doWork(){ myBatch.doWorkInternal(); } Seems to work. Apologies for the weird comment formatting Thanks!!
    – mkdjns
    Oct 21, 2016 at 23:42

You must log in to answer this question.

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