Current Location: Home> Latest Articles> Yii2 Cron Service Setup and Development Guide: Easily Manage Scheduled Tasks

Yii2 Cron Service Setup and Development Guide: Easily Manage Scheduled Tasks

gitbox 2025-06-13

What is Cron Service?

The Cron service is a tool used for scheduling tasks to run at specified intervals. It allows programs to automatically execute specific tasks at designated times. In Yii2, we can use the yii2tech/cron extension to implement Cron service functionality. This extension enables running pre-scheduled Cron jobs using Yii2's console application and outputs relevant information for easy monitoring of the task execution status.

How to Install the yii2tech/cron Extension

First, we need to install the yii2tech/cron extension using Composer:

composer require yii2tech/cron

After the installation is complete, we need to configure the console application to enable this extension. Here's how:

Step 1: Create the Yii2 Console Application

Go to your project root directory and use the following command to create a console application:

php yii2-app console

This will automatically generate a console application named `console` in your project, which will be used to run Cron jobs.

Step 2: Configure the yii2tech/cron Extension

Configuring the yii2tech/cron extension in your console application is simple. Just add the following content to the `console/config/main.php` file:

return [
    //...
    'controllerMap' => [
        //...
        'cron' => \yii2tech\crontab\CronController::class,
    ],
    'components' => [
        'crontab' => [
            'class' => \yii2tech\crontab\CronTab::class,
            'crontabFile' => '@app/config/crontab',
        ],
    ],
];

In this configuration, we enable the CronController provided by the yii2tech/cron extension by adding the `cron` element in the `controllerMap`. Additionally, we configure a `crontab` component that specifies the location of the Cron configuration file.

How to Write a Cron Job

Once the extension is installed and configured, we can start writing Cron jobs. Here are the steps:

Step 1: Define the Cron Job

Defining a Cron job in Yii2 is straightforward. You simply create a class that extends `yii2tech\crontab\CronJob`. Here's an example:

class ClearLogs extends yii2tech\crontab\CronJob
{
    public function getSchedule()
    {
        return '0 * * * *';  // Run at the 0th minute of every hour
    }

    public function run()
    {
        Yii::info('Cron job is running');
        $logPath = 'logs/*.log';
        array_map('unlink', glob($logPath));  // Delete all .log files
    }
}

The above code defines a Cron job called `ClearLogs` that runs every hour at the 0th minute. The `run()` method deletes all `.log` files in the `logs` directory, helping to free up disk space.

Step 2: Add the Cron Job to the Cron Service

Once the Cron job is defined, we need to add it to the Cron service to enable scheduled execution. Here's how:

Sub-step 1: Write the Cron Configuration File

In the `console/config` directory, create a file named `crontab`, and add the Cron job scheduling information. For example:

# crontab format:
# * * * * * command
# Usage:
# {schedule} {command}
# Clean up logs every hour
0 * * * * php {yii} clear-logs
# Clean up cache at 3:00 AM every day
0 3 * * * php {yii} cache/flush-all

In this file, we define the schedule for two Cron tasks: one for cleaning logs every hour and another for flushing the cache at 3:00 AM daily. The `{yii}` placeholder is used to run Yii2 console commands.

Sub-step 2: Run the Cron Service

After configuring the Cron jobs, we can start the Cron service to execute the scheduled tasks. In the command line, navigate to your project root directory and run the following command:

php yii cron

Once started, the Cron tasks will run in the background according to their schedules, and you can monitor the execution status in the console.

Conclusion

Cron services are a valuable tool that can help automate scheduled tasks, saving time and effort. In Yii2, we can easily implement Cron functionality using the `yii2tech/cron` extension. By simply defining Cron job classes and configuration files, we can automate various tasks. This approach helps improve development efficiency and reduces repetitive operations. We hope this article was helpful to you! Thank you for reading!