Rafael Becerra Blasco
Rafael Becerra Blasco

Reputation: 31

Right implementation of cron job in phalcon

What is the right way of implementing cron jobs using phalcon php framework?

I've been trying the Sid\Phalcon\Cron library and reading the docs over and over again and I can't figure out how to get the library running.

I got a Phalcon CLI task running Ok, the idea is create a cron job to execute that task.

This is my code:

        $this->app->di->set(
            "cron_notify",
            function () {
                $cron = new \Sid\Phalcon\Cron\Manager();
                 $cron->add(
                    new \Sid\Phalcon\Cron\Job\System(
                        "* 8 * * *",
                        "php console.php mytask action"
                    )
                );
            });

What else I need to do? I also attach the console to the DI with:

$console = new \Phalcon\Cli\Console();
$di->setShared("console", $console);

I also tried adding the cron this way:

$cron->add(
            new \Sid\Phalcon\Cron\Job\Phalcon(
                "0 * * * *",
                [
                    "task"   => "task",
                    "action" => "action",
                    "params" => "params"
                ]
            )
        );

With the console object attached and calling my phalcon task, but it's not working either.

Upvotes: 1

Views: 979

Answers (1)

toraman
toraman

Reputation: 603

You seem to have set everything up but never told the cron instance to run.

This could be because the documentation page on adding jobs to cron is a little misleading.

You can also add jobs from a Crontab file, such as this one:

* * * * * /usr/bin/php /path/to/cli.php cron

...

This looks like adding this crontab entry is an alternative to manually setting jobs with $cron->add(), but it's not. It's the first step to what comes after. You have to actually add this in a crontab and get the task cron run every minute which handles all the other jobs defined in the \Sid\Phalcon\Cron\Manager service.

In order for your application to run a job (or anything for that matter), the application itself must be initiated with either an http request or a CLI call. Having the jobs and their intervals defined in your app gets them ready to be run at their respective intervals, but you need a main task as an entrypoint to evaluate those intervals and run the jobs when they're due.

The example page in the documentation has this crontab entry again:

* * * * * /usr/bin/php /path/to/cli.php cron

and this task:

class CronTask extends \Phalcon\Cli\Task
{
    public function mainAction()
    {
        $this->cron->runInBackground();
    }
}

This is supposed to be the aforementioned main task to be called in order to do its thing. The crontab entry runs every minute and calls the task cron which in turn checks the job definitions and runs them if they're due.

Upvotes: 0

Related Questions