+1 571-297-6383 | info@sonjara.com

Making the Tasks Run on Time

In Fakoli 3.6.4 we added a new component called scheduled_task. This component provides an easy way to centrally manage tasks that need to be run periodically without user interaction, such as emailing blog digests, or updating the SOLR index for your site.

Defining a Scheduled Task Worker

To define a scheduled task for your Fakoli component, you will first need to subscribe to the RegisterScheduledTaskWorkers event in your component's manifest file:

static function subscribeToEvents()
    return array(
         "RegisterScheduledTaskWorkers" => array(BlogManager, registerScheduledTaskWorkers)

Your registration method can register as many workers as you like for your component. Give each worker a human-readable name so that it can be easily recognised when managing the tasks in the site admin. The task worker is just a method or function that will be called to process your task at its scheduled time.   

static function registerScheduledTaskWorkers()
    ScheduledTaskManager::registerWorker("blog", "Send Digests", array(BlogManager, sendDigests));

The method itself can use any Fakoli feature. In this case, we instantiate a BlogSubscriptionManager object, and use it to send out any pending digests:

static function sendDigests()
    $mgr = new BlogSubscriptionManager();

Any output your worker sends to the output buffer is captured into a log entry that is accessible from the Scheduled Tasks page in admin section. Additionally you can return a text string to indicate the end state (i.e. "Success", or "n entries processed"). If an unhandled exception is thrown during processing, the exception message is automatically captured and reported as the exit state.

Testing your Scheduled Task Worker

While you are developing and debugging your scheduled tasks, you probably won't want to sit around for an hour or more waiting for them to execute. Fortunately you can trigger the task scheduler manually if you are local or logged in as an admin user. To do so, point your browser at:

http://<your site>/action/scheduled_task/run_tasks

Configuring your Server to Run Periodic Tasks

Once you have your tasks running, you will need to set up a cron job to periodically access the task scheduler. To do this:

  • Log into your site's admin section.
  • Click on Authentication Tokens in the User Management section of the admin navigation
  • Create a new token, mapped to the admin user, local IP with the redirect as /action/scheduled_task/run_tasks
  • Add a cron task to make the request against your server via curl or wget. On an Ubuntu server, the easiest way to handle this is to put a script into /etc/cron.hourly. The script should look something like this (where XXXXXX is the token created above):

wget -q http://<your site>/action/auto_login/authenticate?token=XXXXXXX

Enjoy your delayed gratification!

Hello, TinyMCE 4! » « T's and C's PDQ


* indicates required field