Scheduler prevent infinite loop?

Hmm, I need some brain power on this one!

I have a job that requires looping through line items on a quote and adding certain line items. That I’ve managed to get to work fine.

The issue is, I can’t do an on save hook because the relationship between the quote and the quote line items isn’t established yet. An after save hook does not work either.

So I wrote a scheduled task to run in the scheduler to do the math and populate a field in the quote with the result.

At first I created an endless loop for myself because it would run in the scheduler, save the record with the update and then run again.

I solved it like this…

class FinancialTotalsCalc  implements RunnableSchedulerJob
static $already_ran = false;    // static to check against already ran

public function run($arguments) 
	{
	
    // Check if the the function already ran to prevent infinite loop
	if(self::$already_ran == true) return;
      self::$already_ran = true;

..... rest of function.


 // Save the modified quote bean
        $bean->save();
		
		//Signify we have successfully ran the cron job
		return true;	

This works great and prevents it from running more than once. However, my problem now is if I edit a two records during the 1 minute interval when the scheduler runs only one gets updated.

I think I need a different approach to prevent the loop, so it will run on any record but only once per save of a single record.

Any ideas? I just can’t see it!

In some rare instances we do fallback on applying database queries to update records

1 Like

thanks @abuzarfaris do you have any examples you can point me to of updating a value in the current record of a couple of field values using SQL directly?

Something like

$sql="Update contacts set  `status`='$new_value' where id='{$bean->id}'";
$bean->db->query($sql);
1 Like