I am trying to upload documents through Queueable Apex. My intention is to complete all the callouts and then run the logout request to a third party server. I ran into an issue with the exception 'CPU time limit exceeded'. This seems to be the cause:

 List<AsyncApexJob> jobList = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id in :calloutList];
    //while(jobList.size() > 0)
        while (j < jobList.size())

          String status = jobList.get(j).Status;
          //String message = 'Job id: ' + jobList.get(j).Id + ' Status: ' + status;
          //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, message));
          if(status == 'Completed' || status == 'Failed' || status == 'Aborted')
        j = 0;

In short, I am making the page wait until all the requests are complete and then logging out. When I click the button, the page waits and then throws the error. Running the code without this loop does not result the error. What could be the resolution to this problem?


Unless you were to query the jobs through each iteration, you'd run into that problem because you'll never see them complete. Instead, you'd want something more like a do-while:

AsyncApexJob[] jobs;
do {
    jobs = [SELECT ... FROM AsyncApexJob WHERE Id IN :ids AND Status IN ('Queued','Processing')];
} while(!jobs.isEmpty());

Of course, you'll also run into query limits pretty quickly, so you'd probably want to introduce an artificial delay... But, overall, this will run into governor limits one way or another before anything more than about 3 queueable calls could possibly complete, because of the queueable back-off timer.

So, what you'd really want to do is use an actionPoller, or some other client-side script, on your Visualforce page that calls a function to check the status every 15 seconds or so, and when the jobs are all done, then logout.

| improve this answer | |
  • Thanks! I have a question regarding your polling solution. If the jobs are completed and I logout of the server, how do I ensure that the poller is no longer started? i.e. Stop actionpoller when the required task is completed. – dmachop Jul 2 '15 at 19:10
  • 1
    Just cancel the polling. If it's in JavaScript, a clearInterval will do it, or if you're using actionPoller, set enabled to false. You can simply have a variable in your controller for that: public Boolean keepPolling { get; set; } ... <apex:actionPoller enabled="{!keepPolling}"... – sfdcfox Jul 2 '15 at 19:14

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.