2

I want to call a Schedulable class from within a trigger, to execute a batch job after waiting 30 seconds (or 5 seconds, as long as it's long enough to make absolutely sure the initial trigger execution is totally finished).

I'm guessing I would use datetime.now() and a System.Schedule expression to set up the job for x seconds in the future, but how would I set up the correct expression?

I have tried using future methods but sometimes they end up running while the records are still locked and then I get an UNABLE_TO_LOCK_ROW error.

2 Answers 2

3

Future methods, Batchable classes, and Queueable classes all run after the current transaction completes (e.g. your trigger) and all locks have been released. If you're having problems with a future call, you'll probably also have problems with batchable/queueable calls as well. Instead, consider using locking statements by calling SELECT ... FROM ... WHERE Id IN :recordIds FOR UPDATE to make sure you have exclusive access to the records you need access to. This is more reliable than simply trying to change to a different mechanism.

2
  • I see, thanks for the tip. Do you mean to use the FOR UPDATE in the query within the trigger, or in the future method that is calling it? Also, what if I need a future method to delete records?
    – OBerm
    Aug 10, 2015 at 17:20
  • 1
    @Dupe_jockey Use it within the future method, queueable, or batchable method before you attempt to update the record. Future methods can also delete records. This may cause other functions called to realize the record's already deleted.
    – sfdcfox
    Aug 10, 2015 at 17:32
1

Queueable Apex seems more suited to your needs than Schedulable Apex.

Just create a Queueable class like so:

public class AsyncExecutionExample implements Queueable {
    public void execute(QueueableContext context) {
        Account a = new Account(Name='Acme',Phone='(415) 555-1212');
        insert a;        
    }
}

and then have your trigger call it, like so:

ID jobID = System.enqueueJob(new AsyncExecutionExample());
3
  • Ah that looks like just what I need. Thanks for the tip!
    – OBerm
    Aug 10, 2015 at 16:00
  • 1
    Will do, it just makes me wait 10 minutes...
    – OBerm
    Aug 10, 2015 at 16:05
  • @Dupe_jockey If future methods are causing row-lock errors, queueable might do so, too. You should probably consider using locking statements if you're having issues.
    – sfdcfox
    Aug 10, 2015 at 16:20

You must log in to answer this question.

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