Canceling Delayed Async Execution Example

We use this function with the addDelayedAsyncJob function, which allows us, after adding the creation of a job, to delete it for one reason or another. Let’s modify our code from this example.

To our Step let’s add finishRecordProcessing method and inside use a new function.

1public override void finishRecordProcessing(Object record, Object optionalOldRecord){
2    //delete from DelayedAsyncJob if record does not comply with guidlines
3    Account tempAccount = (Account) record;
4    if(tempAccount.Name == 'CanceledAccount'){
5        cancelAsyncRequest(tempAccount.Id);
6    }
7}

So that the step uses finishRecordProcessing method, we need in the method initRecordProcessing change return value:

from:

return false;

to:

return true;

Now when an account is created, its id will be added to the DelayedASyncJob. But if Account name equals ‘CanceledAccount’, then id of this record will be deleted from DelayedASyncJob. Record which was not deleted after 30 minutes will be asynchronously launched, that means, the logic will be done inside the executeAsyncProcess method.

 1public class ConditionalContactGenerator extends forvendi.Step {
 2    public ConditionalContactGenerator () {
 3        super(ConditionalContactGenerator.class.getName());
 4    }
 5 
 6    public override Boolean initRecordProcessing(Object record, Object optionalOldRecord) {
 7        //adding incoming record to the DelayedAsyncJob
 8        getStore().
 9        Account accountRecord = (Account)record;
10        addDelayedAsyncJob(accountRecord.Id, Datetime.now() );
11        return true;
12    }
13
14
15public override void finishRecordProcessing(Object record, Object optionalOldRecord){
16        //delete from DelayedAsyncJob if record does not comply with guidlines
17        Account tempAccount = (Account) record;
18        if(tempAccount.Name == 'CanceledAccount'){
19            cancelAsyncRequest(tempAccount.Id);
20        }
21    }
22 
23    public override void executeAsyncProcess(Map<String, forvendi.AsyncJobInfo> asyncJobsByRecordKey){
24        //for every account record in DelayedAsync insert Contacts
25        List<Contact> contactsToCreate = new List<Contact>();
26        for(String record : asyncJobsByRecordKey.keySet()){
27            contactsToCreate.add(new Contact(LastName = 'Contact ' + System.now(), AccountId = record));
28        }
29        getContext().addToInsert(contactsToCreate);
30    }
31}