Yii 2.0: How to implement cron in Yii 2

9 followers

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="hemctest@gmail.com"]

in windows for test it run as.

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

Official docs for console applications can be seen here.

Total 9 comments

#19415 report it
Temir at 2015/06/26 01:23am
How about basic template?

Since title of the topic is "Yii 2.0: How to implement cron in Yii 2" why don't you cover the implementation of cron in basic template too? Otherwise rename the title to: "Yii 2.0: How to implement cron in Yii 2 Advanced Template"

#18595 report it
Amjad Khan at 2014/11/25 11:07am
cron job problem

In advance app this is the code i have written for the swiftmailer for cron jobs in common/config/main-local.php

'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
           // 'viewPath' => '@common/mail',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => false,
            'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'localhost',
            //'username' => "amjadiqbalkhanniazi@gmail.com",
           // 'password' =>"commented!",
            'port' => '465',
            'encryption' => 'ssl',
        ],
        ],

In advanced app this is the code i have written in console/controllers for the email generation for cron jobs.

<?php
 
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 
namespace console\controllers;
 
use yii\console\Controller;
 
class TestController extends Controller {
 
    public function actionIndex() {
 
 
        \Yii::$app->mailer->compose()
            ->setTo('amjadiqbalkhanniazi@gmail.com')
            ->setFrom(['amjadiqbalkhanniazi@gmail.com' =>'Amjad Iqbal Khan'])
            ->setSubject('This is the test mail,please ignore')
            ->setTextBody('This is the body of the mail')
            ->send();
    }
 
}

after this command

" php /home/username/public_html/mediamail/php yii test"

i m getting following error please help

This is Yii version 2.0.1-dev.
 
The following commands are available:
 
Content-type: text/html
 
Exception 'yii\base\InvalidConfigException' with message 'Unable to determine the entry script file path.'
 
in /home2/cpdipaki/public_html/mediamail/vendor/yiisoft/yii2/base/Request.php:62
 
Stack trace:
#0 /home2/cpdipaki/public_html/mediamail/vendor/yiisoft/yii2/base/Component.php(130): yii\base\Request->getScriptFile()
#1 /home2/cpdipaki/public_html/mediamail/vendor/yiisoft/yii2/console/controllers/HelpController.php(369): yii\base\Component->__get('scriptFile')
#2 /home2/cpdipaki/public_html/mediamail/vendor/yiisoft/yii2/console/controllers/HelpController.php(199): yii\console\controllers\HelpController->getScriptName()
#3 /home2/cpdipaki/public_html/mediamail/vendor/yiisoft/yii2/console/controllers/HelpController.php(67): yii\console\controllers\HelpController->getDefaultHelp()
#4 [internal function]: yii\console\controllers\HelpController->actionIndex(NULL)
#5 /home2/cpdipaki/public_html/mediamail/vendor/yiisoft/yii2/base/InlineAction.php(55): call_user_func_array(Array, Array)
#6 /home2/cpdipaki/public_html/mediamail/vendor/yiisoft/yii2/base/Controller.php(151): yii\base\InlineAction->runWithParams(Array)
#7 /home2/cpdipaki/public_html/mediamail/vendor/yiisoft/yii2/console/Controller.php(91): yii\base\Controller->runAction('', Array)
#8 /home2/cpdipaki/public_html/mediamail/vendor/yiisoft/yii2/base/Module.php(455): yii\console\Controller->runAction('', Array)
#9 /home2/cpdipaki/public_html/mediamail/vendor/yiisoft/yii2/console/Application.php(161): yii\base\Module->runAction('', Array)
#10 /home2/cpdipaki/public_html/mediamail/vendor/yiisoft/yii2/console/Application.php(137): yii\console\Application->runAction('', Array)
#11 /home2/cpdipaki/public_html/mediamail/vendor/yiisoft/yii2/base/Application.php(375): yii\console\Application->handleRequest(Object(yii\console\Request))
#12 /home2/cpdipaki/public_html/mediamail/yii(30): yii\base\Application->run()
#13 {main}
#17192 report it
hemc at 2014/05/12 01:40am
Re- command description

Thanks Shahram. I have downloaded the zip files for both basic and advanced template and i can see the class description when i run "yii". Please check if you are using latest files for advanced template.

#17185 report it
Shahram at 2014/05/10 04:13pm
command description

Thanks for writing.

I tried it, It is working fine, but when I use "yii" command, I can not see the class description in advanced template. In basic template I can see PHPDOC but not in advanced one.

#16985 report it
Ahamed Rifaideen at 2014/04/18 05:40am
No Console Access

sorry currently no console access

#16984 report it
hemc at 2014/04/18 05:30am
How to Use Console in Hosted Server

@ Ahamed Rifaideen Do you have access to console? If not contact to your hosting provider. Once you have access edit the crontab file as in ubuntu i use

sudo crontab -e

and add the command to run files in it. ex. to run a command on every 2 hour i have added

0 */2 * * * ~/sites/www/yii2/yii test
#16983 report it
Ahamed Rifaideen at 2014/04/18 05:17am
How to Use Console in Hosted Server

everything is ok but how do i run a console application on live website

#16977 report it
hemc at 2014/04/17 10:30am
can use models in 1.x also

Thanks. In Yii 1.x also, you can use models. We are using models in 1.1 boilerplate by importing models in console/config/main.php

#16976 report it
HarikrishnanP at 2014/04/17 10:23am
Really helpful.

before I used normal php program as cron. I could't use models so I had to write lot of sql queries. It seems cool!

Leave a comment

Please to leave your comment.

Write new article
  • Written by: hemc
  • Category: How-tos
  • Yii Version: 2.0
  • Votes: +9
  • Viewed: 15,421 times
  • Created on: Apr 17, 2014
  • Last updated: never
  • Tags: cron, yii2, console