Search code examples
zend-frameworkcron-task

directory structure for queued jobs (cron jobs) in zend framework


I found quite a few posts related to directory structure and cron jobs in Zend Framework, and yet no clear answer :(

I have the following code to create a job that sends an email. Works perfectly as long as the script (emailNotification.php) is under /jobs in the public directory.

public function emailAction() {

    $request = $this->getRequest();
    if ($request->isPost()) {

        $emailFrom = $request->getPost('emailFrom');
        $messageFrom = $request->getPost('messageFrom');
        $subject = $request->getPost('Sub');
        $emailTo = $request->getPost('emailTo');

        // create a queued job
        date_default_timezone_set('UTC');            
        $q = new ZendJobQueue();
        $ts = date('Y-m-d H:i:s', time()+30);
        $id=$q->createHttpJob('jobs/emailNotification.php',array('emailFrom'=>$emailFrom,
                'messageFrom'=>$messageFrom,'subject'=>$subject,
                'emailTo'=>$emailTo),
                array('name'=>'email notification using a single job execution scheduled to run after 30 seconds','schedule_time'=>$ts));

        if(!$id)
            $this->_helper->json(array('status' => 'success', 'message' => "Queued job didn't work."));

        $this->_helper->json(array('status' => 'success', 'message' => "Email sent successfully."));
    } // request->isPost()

}// function emailAction

My directory structure is the default structure created by ZF:

  [MyProject]
     [application]
     [data]
     [docs]
     [library]
     [public]
        index.php
     [scripts]

How do I modify createHttpJob to run the script from a different directory, say scripts/jobs instead of public/jobs? Is there anything else I should be doing?


Solution

  • It really depends how you are calling the cron job, and how much bootstrapping you are doing at the start of that script (if any). I would change your code to:

    $id=$q->createHttpJob(APPLICATION_PATH.'/../scripts/jobs/emailNotification.php', [...]
    

    to start with, then all you need to do is ensure APPLICATION_PATH is set in your cron script.