• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

Deferred System

Uniphix

Active member
#1
Can a developer or someone explain how to use this system correctly? I can't for the life of me figure out how it all works so that I can create some background tasks that are heavy on our system. Any explanation would probably not just help me but any other xf developers out there...

Thanks
 

karll

Well-known member
#2
I "accidentally" used this in the latest feature on my unwatch add-on. I made it work in the end the way I wanted it to (I think!), but I too would be interested in an explanation from someone knowledgeable.
 

Daniel Hood

Well-known member
#3
Basically the concept is to delay the execution of intense code. If you have a big task to do like recalculating the position of every post or something, you wouldn't want that to be done while the page is loading for the user. So instead of doing it in the datawriter's _postSave() function, you would add this line to the _postSave() function:

Code:
XenForo_Application::defer($className, $data); #$className is the name of the class that holds your deferred functionality, $data is an array of data that you need to execute with.
Then you make a deferred file: for example: "MyAddon_Deferred_Action.php". Now when the deferred.php file runs, it's going to call MyAddon/Deferred/Action.php with the function being execute();

PHP:
class MyAddon_Deferred_Action extends XenForo_Deferred_Abstract
{
 public function execute(array $deferred, array $data, $targetRunTime, &$status)
 { 
   #this holds your deferred script 
 } 
}
Check out the files in XenForo/Deferred/ to see how they handle batching and what not.
 

karll

Well-known member
#4
Thanks for the explanation. Well, the thing that confused me was that my execute function was called again and again and again ...

It seems pretty obvious now, but my problem was solved by returning false when I wanted it to stop, and otherwise return the $data array with the parameters for the next iteration.
 

Daniel Hood

Well-known member
#5
Oh, yeah I should have included that. It needs to return whether or not to do another batch.

I wish there was official XenForo documentation, although their commenting is very helpful.