Wednesday, November 7, 2018

Asynchronous Bean Saves

Why I needed this

In my SugarCRM installation I have many logic hooks that update values in other modules.  For example, when you save a note it, in the before_save logic hook, it updates a "Last Note Update" field (among others) in the related Case.  So that means that you save the note and it has to run all the logic hooks, workflows, advanced workflows and SugarLogic on that note and then it would have to run all that stuff on the related case as well, all while the user waits for their save to finish.

In the past to avoid the overhead of a bean save I would just update the related bean with a direct SQL call.  But this means you lose out on logic_hooks, workflow and all the rest.  So if you can off-load all that extra bean save overhead to a JobQueue job, it will speed up saves while not impacting workflow or logic hooks the way a direct SQL call would.  The JobQueue is explained in the developer guide here.

So this is an example of the kind of code I am talking about and the new code I use



The 'new' code would call a function I have placed in a file called custom/Extension/application/Ext/Utils/UpdateBean.php.  
This makes it available anywhere in the app. Custom utilities are in the developer guide here.  That file looks like this

That function submits a job to the job queue and it will run the next time cron runs.  So you bean save might be delayed by a minute but your user doesn't have to sit through it.  The final file, the job itself is in a file called custom/Extension/modules/Schedulers/Ext/ScheduledTasks/updateBeanJob.php and looks like this



So thats it, easy Asynchronous bean saves.