简体   繁体   中英

Yii2 set cron job using console controller

In Yii2.0 i have set cron job in console controller for send mail . Its working when i execute cmd php yii cron in prompt.

I need to execute this file every hour. Cpanel not executing every hour why?

You need to be using absolute paths to both php and yii:

* */1 * * * /usr/bin/php /var/www/mysite/yii controller/action

That should do the trick - provided that you supply the correct paths.

To find out what the full path to php is, run this in a console prompt:

which php

You can set the command like this in cron for cpanel

usr/bin/curl -k http://xxxxxxx.com/cron

OR

wget -O /dev/null http://xxxxxxx.com/cron

And you time settings should be

0 * * * *

Thanks

0 */3 * * * your command here

Create console application

In advance template there is already a file yii. And there is no need to run it as php, it is Linux script.

Create cron service command

Create a controller in console/controllers

I have created as TestController.php

<?php

namespace console\controllers;

use yii\console\Controller;

/**
 * Test controller
 */
class TestController extends Controller {

    public function actionIndex() {
        echo "cron service runnning";
    }

    public function actionMail($to) {
        echo "Sending mail to " . $to;
    }

}
?>

This controller should be use the console controller name space

use yii\console\Controller;

How to run it

run it as

yii test

I have test it on windows by running

D:\xampp\htdocs\yii2>d:\xampp\php\php yii test
cron service runnning
D:\xampp\htdocs\yii2>

How to pass params

yii test/mail [--to="ali@hackers.com.pk"]

in windows for test it run as.

D:\xampp\htdocs\yii2>d:\xampp\php\php yii test/mail [--to="ali@hackers.com.pk"]
Sending mail to [--to="ali@hackers.com.pk"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM