2017 © Pedro Peláez
 

yii2-extension yii2-scheduler

A scheduled task runner for Yii2 applications

image

webtoolsnz/yii2-scheduler

A scheduled task runner for Yii2 applications

  • Monday, July 3, 2017
  • by badams
  • Repository
  • 8 Watchers
  • 8 Stars
  • 905 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 3 Forks
  • 3 Open issues
  • 19 Versions
  • 20 % Grown

The README.md

yii2-scheduler

Software License Build Status Coverage Status Quality Score, (*1)

A scheduled task manager for yii2, (*2)

Installation

The preferred way to install this extension is through composer., (*3)

Install using the following command., (*4)

$ composer require webtoolsnz/yii2-scheduler

Now that the package has been installed you need to configure the module in your application, (*5)

The config/console.php file should be updated to reflect the changes below, (*6)

    'bootstrap' => ['log', 'scheduler'],
    'modules' => [
        'scheduler' => ['class' => 'webtoolsnz\scheduler\Module'],
    ],
    'components' => [
        'errorHandler' => [
            'class' => 'webtoolsnz\scheduler\ErrorHandler'
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\EmailTarget',
                    'mailer' =>'mailer',
                    'levels' => ['error', 'warning'],
                    'message' => [
                        'to' => ['admin@example.com'],
                        'from' => [$params['adminEmail']],
                        'subject' => 'Scheduler Error - ####SERVERNAME####'
                    ],
                    'except' => [
                    ],
                ],
            ],
        ],
    ]

also add this to the top of your config/console.php file, (*7)

\yii\base\Event::on(
    \webtoolsnz\scheduler\console\SchedulerController::className(),
    \webtoolsnz\scheduler\events\SchedulerEvent::EVENT_AFTER_RUN,
    function ($event) {
        if (!$event->success) {
            foreach($event->exceptions as $exception) {
                throw $exception;
            }
        }
    }
);

To implement the GUI for scheduler also add the following to your config/web.php, (*8)

    'bootstrap' => ['log', 'scheduler'],
    'modules' => [
        'scheduler' => ['class' => 'webtoolsnz\scheduler\Module'],
    ],

After the configuration files have been updated, a tasks directory will need to be created in the root of your project., (*9)

Run the database migrations, which will create the necessary tables for scheduler, (*10)

php yii migrate up --migrationPath=vendor/webtoolsnz/yii2-scheduler/src/migrations

Add a controller, (*11)

<?php

namespace app\modules\admin\controllers;

use yii\web\Controller;

/**
 * Class SchedulerController
 * @package app\modules\admin\controllers
 */
class SchedulerController extends Controller
{
    public function actions()
    {
        return [
            'index' => [
                'class' => 'webtoolsnz\scheduler\actions\IndexAction',
                'view' => '@scheduler/views/index',
            ],
            'update' => [
                'class' => 'webtoolsnz\scheduler\actions\UpdateAction',
                'view' => '@scheduler/views/update',
            ],
            'view-log' => [
                'class' => 'webtoolsnz\scheduler\actions\ViewLogAction',
                'view' => '@scheduler/views/view-log',
            ],
        ];
    }
}

Example Task

You can now create your first task using scheduler, create the file AlphabetTask.php inside the tasks directory in your project root., (*12)

Paste the below code into your task:, (*13)

<?php
namespace app\tasks;

/**
 * Class AlphabetTask
 * @package app\tasks
 */
class AlphabetTask extends \webtoolsnz\scheduler\Task
{
    public $description = 'Prints the alphabet';
    public $schedule = '0 * * * *';
    public function run()
    {
        foreach (range('A', 'Z') as $letter) {
            echo $letter;
        }
    }
}

The above code defines a simple task that runs at the start of every hour, and prints the alphabet., (*14)

The $schedule property of this class defines how often the task will run, these are simply Cron Expression, (*15)

Running the tasks

Scheduler provides an intuitive CLI for executing tasks, below are some examples, (*16)

 # list all tasks and their status
 $ php yii scheduler

 # run the task if due
 $ php yii scheduler/run --taskName=AlphabetTask

 # force the task to run regardless of schedule
 $ php yii scheduler/run --taskName=AlphabetTask --force

 # run all tasks
 $ php yii scheduler/run-all

 # force all tasks to run
 $ php yii scheduler/run-all --force

In order to have your tasks run automatically simply setup a crontab like so, (*17)

*/5 * * * * admin php /path/to/my/app/yii scheduler/run-all > /dev/null &

Events & Errors

Events are thrown before and running individual tasks as well as at a global level for multiple tasks, (*18)

Task Level, (*19)

Event::on(AlphabetTask::className(), AlphabetTask::EVENT_BEFORE_RUN, function ($event) {
    Yii::trace($event->task->className . ' is about to run');
});
Event::on(AlphabetTask::className(), AlphabetTask::EVENT_AFTER_RUN, function ($event) {
    Yii::trace($event->task->className . ' just ran '.($event->success ? 'successfully' : 'and failed'));
});

or at the global level, to throw errors in /yii, (*20)

$application->on(\webtoolsnz\scheduler\events\SchedulerEvent::EVENT_AFTER_RUN, function ($event) {
    if (!$event->success) {
        foreach($event->exceptions as $exception) {
            throw $exception;
        }
    }
});

You could throw the exceptions at the task level, however this will prevent further tasks from running., (*21)

License

The MIT License (MIT). Please see LICENSE for more information., (*22)

The Versions