NOTE: Updated to remove before mentioned hack for making job class available, now you can do this via the Ext Framework
I’ve many times over seen logic hooks like the below being used to send out an alert email on save to an Account record.
This is a pretty effective way to send out such an email, but if you are the end user trying to save records you’ll notice it can make the save time a bit longer as the entire send email process in happening synchronously with the save. In other words, in order for the save to finish to email must be successfully sent, which can take a few seconds to complete. Not exactly a great user experience.
The Job Queue, a new developer feature in Sugar 6.5, can help solve this problem. What this enables you to do is to send longer running jobs, such as sending emails, calling web services, or doing other resource intensive jobs that can be done asynchronously to be handled by the cron in the background. To setup the cron to run, follow this support article.
Now let’s look at how to change the above example to take advantage of the Job Queue. First off, let’s re-write the logic hook above to instead push the work to be done into the Job Queue…
The key pieces above are creating the new Job and pushing it into the queue to run.
Now we just need to define the Job. All that you need to do here is create a new class that implements ‘RunnableSchedulerJob’, which requires implementing it’s two abstract methods of setJob() and run(). You put this file in the custom/Extensions/modules/Schedulers/Ext/ScheduledTasks/ directory with the name AccountAlertJob.php
You’ll note in the logic hook where we defined the job we set the $data property to be the record id. This $data property is then passed to the run() call, so we have the context from the logic hook to run the job in the background.
With this, the next time the cron is called, the alert email will be sent out, and all of you users will have much faster record saves.