How to implement cron in Yii 2

  1. Create console application
  2. Create cron service command
  3. How to run it
  4. How to pass params

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


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

How to pass params

yii test/mail [--to=""]

in windows for test it run as.

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

Official docs for console applications can be seen here.

3 0
Viewed: 100 512 times
Version: 2.0
Category: How-tos
Tags: console, cron, yii2
Written by: hemc
Last updated by: hemc
Created on: Apr 17, 2014
Last updated: 10 years ago
Update Article


View all history

Related Articles