Let the platform do the work

Queuing Logic Hook Actions

Overview

This example will demonstrate how to pass tasks to the job queue. This enables you to send longer running jobs such as sending emails, calling web services, or doing other resource intensive jobs to be handled asynchronously by the cron in the background.

Example

This example will queue an email to be sent out by the cron when an account record is saved. First, we will create a before_save logic hook on accounts.

./custom/modules/Accounts/logic_hooks.php

<?php

    $hook_version = 1; 
    $hook_array = Array(); 

    $hook_array['before_save'][] = Array();
    $hook_array['before_save'][] = Array(
        1, 
        'Queue Job Example', 
        'custom/modules/Accounts/Accounts_Save.php', 
        'Accounts_Save', 
        'QueueJob'
    );

?>

In our logic hook, we will create a new SchedulersJob and submit it to the SugarJobQueue targeting our custom AccountAlertJob that we will create next.

./custom/modules/Accounts/Accounts_Save.php

<?php

    if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
    
require_once 'include/SugarQueue/SugarJobQueue.php';
class Accounts_Save { function QueueJob(&$bean, $event, $arguments) { //create the new job $job = new SchedulersJob(); //job name $job->name = "Account Alert Job - {$bean->name}"; //data we are passing to the job $job->data = $bean->id; //function to call $job->target = "function::AccountAlertJob"; global $current_user; //set the user the job runs as $job->assigned_user_id = $current_user->id; //push into the queue to run $jq = new SugarJobQueue(); $jobid = $jq->submitJob($job); } } ?>

Next, we will need to define the Job. This will be done by creating a new function to execute our code. We will put this file in the ./custom/Extension/modules/Schedulers/Ext/ScheduledTasks/ directory with the name AccountAlertJob.php.

./custom/Extension/modules/Schedulers/Ext/ScheduledTasks/AccountAlertJob.php

<?php

function AccountAlertJob($job)
{
    if (!empty($job->data))
    {
        $bean = BeanFactory::getBean('Accounts', $job->data);

        $emailObj = new Email();
        $defaults = $emailObj->getSystemDefaultEmail();
        $mail = new SugarPHPMailer();
        $mail->setMailerForSystem();
        $mail->From = $defaults['email'];
        $mail->FromName = $defaults['name'];
        $mail->Subject = from_html($bean->name);
        $mail->Body = from_html("Email alert that '{$bean->name}' was saved");
        $mail->prepForOutbound();
        $mail->AddAddress('example@sugar.crm');

        if($mail->Send())
        {
            //return true for completed
            return true;
        }
    }

    return false;
}

Finally, navigate to Admin / Repair / Quick Repair and Rebuild. The system will then generate the file ./custom/modules/Schedulers/Ext/ScheduledTasks/scheduledtasks.ext.php containing our new function. We are now able to queue and run the scheduler job from a logic hook.

Topics