Yii 2.0 Cron Job

Yii 2.0 Cron Job

In this post I want to teach you how to add a cron job to your Yii 2.0 project. What is a Cron Job? Cron Jobs are scheduled jobs.


In this post I want to teach you how to add a cron job to your Yii 2.0 project.

What is a Cron Job?

Cron Jobs are scheduled jobs. When developing a website you can define these cron jobs for your website. These jobs run periodically at fixed times, dates, or intervals.

Why do we need to use Cron Jobs?

As an example, if you have a blog, sometimes you need your post to be published at a specific time or date. But it is hard to publish it yourself at that time. Cron job, does that for you. You can add a cron job to fetch all unpublished posts and check their publish time, if the time has passed, it will publish it for you.

How to add a Cron Job to your Yii 2.0 project?

You have a folder called commands in you project. Open the folder. Inside that folder add a file called CronControllr.php (The name is an example, you can name it something else). Inside this file, you can add your cron jobs.

Open the file and add the following code to it:

<?php

    namespace app\commands;

    use yii\console\Controller;

    class CronController extends Controller
    {

        public function actionIndex()
        {
        }

    }

Now we have a Cron Controller to handle our request with an action called index.

We want the action to fetch all unpublished posts from Post Model and check its publish date. If the date has passed, then publish it. We need to add the following code:

<?php

    namespace app\commands;

    use yii\console\Controller;

    class CronController extends Controller
    {

        public function actionIndex()
        {
          $get_posts=\app\models\Post::find()->where(['status'=>'unpublished'])->all();
          foreach($get_posts as $post){
            if($post->publish_timestamp<time()){
              $post->status='published';
              $post->save();
            }
          }
        }

    }

Now in your Admin Control Panel, such as CPanel, add its url to your cron jobs and set an execution time for it. (Its url would be php (or path to php) /path/to/yii cron/index)