thamtech / yii2-scheduler
为 Yii2 应用程序提供的配置驱动的计划任务运行器
Requires
- dragonmantank/cron-expression: ~1.2 || ~2.0 || ~3.0
- yiisoft/yii2: ^2.0.14 <2.1
Requires (Dev)
README
为 Yii2 提供的配置驱动的计划任务管理器。
这是从 webtoolsnz/yii2-scheduler 改编而来,以提供更配置驱动的方案。
主要区别
- webtoolsnz/yii2-scheduler
- 自动在
@app/tasks
文件夹中检索任务类 - 一旦在数据库表中建立了任务,数据库中的
active
值控制任务是否启用,而不是 Task 类中的active
属性
- 自动在
- thamtech/yii2-scheduler
- 任务明确地作为调度模块配置的一部分定义
- Task 实例的
active
属性控制任务是否启用(因此可以编程控制,而不仅仅是通过调度器的数据库表)
安装
安装此扩展的首选方法是使用 composer。
使用以下命令安装。
$ composer require thamtech/yii2-scheduler
现在包已安装,您需要配置应用程序中的模块。
应更新 config/console.php
文件(或您使用不同 Yii 项目模板的等效控制台配置文件),以反映以下更改
<?php [ 'bootstrap' => ['log', 'scheduler'], 'modules' => [ 'scheduler' => [ 'class' => 'thamtech\scheduler\Module', // optional: define a mutex component to acquire a lock // while executing tasks so only one execution of schedule tasks // can be running at a time. 'mutex' => [ 'class' => 'yii\mutex\MysqlMutex', ], // OR optionally reference an existing application mutex component, // for example, one named "mutex": // 'mutex' => 'mutex', ], ], 'components' => [ 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ [ 'class' => 'yii\log\EmailTarget', 'mailer' =>'mailer', 'levels' => ['error', 'warning'], 'message' => [ 'to' => ['alets@example.com'], 'from' => ['app@example.com'], 'subject' => 'Scheduler Error - ####SERVERNAME####' ], 'except' => [ ], ], ], ], ], ];
还要将以下内容添加到 config/console.php
文件的顶部
\yii\base\Event::on( \thamtech\scheduler\console\SchedulerController::className(), \thamtech\scheduler\events\SchedulerEvent::EVENT_AFTER_RUN, function ($event) { if (!$event->success) { foreach($event->exceptions as $exception) { throw $exception; } } } );
运行数据库迁移,这将创建必要的表
php yii migrate up --migrationPath=vendor/thamtech/yii2-scheduler/src/migrations
为了实现查看计划任务和日志的 GUI,添加一个网络控制器
<?php namespace app\modules\admin\controllers; use yii\web\Controller; /** * SchedulerController has a set of actions for viewing scheduled tasks and * their logs. */ class SchedulerController extends Controller { public function actions() { return [ 'index' => [ 'class' => 'thamtech\scheduler\actions\IndexAction', 'view' => '@scheduler/views/index', ], 'view' => [ 'class' => 'thamtech\scheduler\actions\ViewAction', 'view' => '@scheduler/views/view', ], 'view-log' => [ 'class' => 'thamtech\scheduler\actions\ViewLogAction', 'view' => '@scheduler/views/view-log', ], ]; } }
示例任务
现在您可以使用调度器创建第一个任务。在本例中,我们将在应用程序的 tasks
目录中创建 ConcatStringsTask.php
。
<?php namespace app\tasks; /** * Task to print a concatenation of the specified strings. */ class ConcatStringsTask extends \thamtech\scheduler\Task { /** * @var string task description */ public $description = 'Prints a concatenation of the specified strings'; /** * @var string[] the strings to be concatenated */ public $strings = []; /** * @inheritdoc */ public function run() { echo join('', $this->strings); } }
在控制台应用程序的 scheduler
模块配置中定义任务
<?php 'modules' => [ 'scheduler' => [ 'class' => 'thamtech\scheduler\Module', 'tasks' => [ 'hello-world' => [ 'class' => 'app\tasks\ConcatStringsTask', 'displayName' => 'Hello World Task', 'schedule' => '0 * * * *', 'strings' => ['Hello', ' ', 'World'], ], ], ], ],
上述代码定义了一个简单的任务,它每小时开始运行并打印 "Hello World"。另一种方法是直接在任务类(如 schedule
)中硬编码一些或所有属性。然而,此示例更符合项目的目标,即更配置驱动的任务定义方法。
此类的 $schedule
属性定义了任务将运行的频率,这些是简单的 Cron 表达式
您可以在 scheduler
模块配置中定义多个任务实例,并且对于多个实例重用相同的 Task 类是可以的。以下是一个具有额外 "Foo Bar" 任务示例,该任务每小时在半小时运行
<?php 'modules' => [ 'scheduler' => [ 'class' => 'thamtech\scheduler\Module', 'tasks' => [ 'hello-world' => [ 'class' => 'app\tasks\ConcatStringsTask', 'displayName' => 'Hello World Task', 'schedule' => '0 * * * *', 'strings' => ['Hello', ' ', 'World'], ], 'foo-bar' => [ 'class' => 'app\tasks\ConcatStringsTask', 'displayName' => 'Foo Bar Task', 'schedule' => '30 * * * *', 'strings' => ['Foo', ' ', 'Bar'], ], ], ], ],
运行任务
调度器提供了一种直观的 CLI 来执行任务,以下是一些示例
# list all tasks and their status $ php yii scheduler # run the task if due $ php yii scheduler/run --taskName=hello-world # force the task to run regardless of schedule $ php yii scheduler/run --taskName=hello-world --force # run all tasks $ php yii scheduler/run-all # force all tasks to run $ php yii scheduler/run-all --force
要使任务自动运行,只需设置类似以下的 crontab
*/5 * * * * admin php /path/to/my/app/yii scheduler/run-all > /dev/null &
事件 & 错误
事件在运行单个任务之前和之后以及全局层面上的多个任务时抛出
任务级别
<?php 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')); });
或在全局级别,在 /yii
中抛出错误
<?php $application->on(\thamtech\scheduler\events\SchedulerEvent::EVENT_AFTER_RUN, function ($event) { if (!$event->success) { foreach($event->exceptions as $exception) { throw $exception; } } });
您可以在任务级别抛出异常,但是这将阻止进一步的任务运行。
许可证
MIT许可证(MIT)。有关更多信息,请参阅LICENSE.md。