There are different ways to offload long-running processes to asynchronous apex: we got future calls, scheduled Apex, batch Apex and, more recently, Queueable Apex.

They are all good to launch "fire and forget" methods: they all have a return type of void.

Is there any other asynchronous mechanism where we can offload some work to an asynchronous method, then wait until it finishes to continue processing? I would like to avoid callbacks, but rather sleep one thread until the asynchronous processing has finished.

Or is that something that has been deliberately disabled by Salesforce to avoid running out of threads?


Salesforce/apex does not support threads. There is no way to synchronize asynchronous apex. But if you want as a workaround, you can update some backend field in some object from the asynchronous apex and write a trigger on the object. Then using trigger you can continue remaining execution. It is not recommended.

Note - If you are okay to wait till asynchronous process is complete, use synchronous code instead of asynchronous(if you are not hitting governor limits).

  • Curious - why is using a trigger called from an asynchronous call not recommended? – Brian Mansfield Mar 30 '15 at 19:00
  • It is not the best way to do. Resort it as last way only. If possible keep it as synchronous process and directly complete the whole process, it will be the fastest way to achieve. – Victor Mar 30 '15 at 21:35
  • Hi, Victor, that's what I thought. The workaround you suggest (running a trigger from a custom object) is similar to calling a callback. It does not happen on the same (original) thread. And, yes, the reason why we use async is purely to avoid hitting governor limits. – mkorman Apr 1 '15 at 10:09

Thinking in Threads and Processes might not help directly, but you could try use a Custom Object (let's call it AT__c) to track the progress.

  • create an after insert trigger on AT__c too. There add the code which you like to have executed on completion.
  • insert a new AT__c record as a very last action in your async code. The above trigger will fire.
  • Using the record, you can even provide some "Arguments" as fields (if you need it)
  • from time to time you could wipe all AT__c and in the meantime you have a nice execution log as a side-effect

So you can intercept the async completion and got some code fired without repetitively query the status. There is not even a sleeping thread required.

  • @mkorman n.b. if the AT__c trigger fails with a Validation rule or an uncaught exception, then it will throw an exception back to the async process which will have to be dealt with. – cropredy Mar 30 '15 at 19:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.