trentrichardson/cakephp-scheduler

使 CakePHP 中的任务调度变得非常简单。

3.0.4 2016-01-09 20:50 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:56:55 UTC


README

使 CakePHP 中的任务调度变得非常简单。

作者

Trent Richardson [http://trentrichardson.com]

许可证

版权所有 2015 Trent Richardson

您可以在 MIT 许可证下使用此项目。 http://trentrichardson.com/Impromptu/MIT-LICENSE.txt

工作原理

SchedulerShell 通过为项目安排一个 cron(SchedulerShell)来工作。然后在 bootstrap.php 中,您可以为您所有的任务创建间隔。部署新的计划任务现在变得更容易;一个 crontab 条目执行所有任务。

安装

此 Shell 是为 CakePHP 3 开发的。

Composer 安装(推荐)

在您的项目 composer.json 文件中,将此添加到您的 require

"trentrichardson/cakephp-scheduler": "~3.0"

手动安装

将 Scheduler 插件复制到您的 App/Plugin 文件夹中,并将文件夹重命名为 Scheduler。

加载插件

在您的 bootstrap.php 文件中添加以下任一项:

Plugin::loadAll();

Plugin::load('Scheduler',['autoload'=>true]);

通过最短的间隔为 SchedulerShell.php 安排单个系统 cron。例如,如果您有 5 个任务,最频繁运行的是每 5 分钟,那么请安排此 cron 至少每 5 分钟运行一次。更多信息请参阅 Shells as Cron Jobs

示例 cron 作业

*/5 * * * * cd /path/to/app && bin/cake Scheduler.Scheduler

这将每 5 分钟运行一次 SchedulerShell。

现在一旦安排了这个 shell,我们就可以将条目添加到 bootstrap.php 中。假设我们想每天早上 5 点调度 CleanUp 任务,每 15 分钟调度一次 NewsletterTask。

Configure::write('SchedulerShell.jobs', array(
	'CleanUp' => array('interval' => 'next day 5:00', 'task' => 'CleanUp'),// tomorrow at 5am
	'Newsletters' => array('interval' => 'PT15M', 'task' => 'Newsletter') //every 15 minutes
));

每个条目的密钥将用于存储之前的运行。 这些必须是唯一的

interval 可以通过两种方式设置。

  1. 对于一天中的特定时间,我们使用 PHP 的 相对时间格式:"下一天 5:00"。

  2. 要使用间隔实现 "每 15 分钟",我们使用 DateInterval 字符串格式:"PT15M"。

task 只是 Task 的名称。

您可以传递一些可选参数:"action" 和 "pass"。

action 默认为 "execute",这是您指定任务中要调用的方法名称。

pass 默认为 array(),这是传递给 "action" 的参数数组。

Configure::write('SchedulerShell.jobs', array(
	'CleanUp' => array('interval' => 'next day 5:00', 'task' => 'CleanUp', 'action' => 'execute', 'pass' => array()),
	'Newsletters' => array('interval' => 'PT15M', 'task' => 'Newsletter', 'action' => 'execute', 'pass' => array())
));

结果存储

SchedulerShell 通过一个 json 文件跟踪每次运行。默认情况下,它存储在 TMP 中,名为 "cron_scheduler.json"。

如果您需要更改这些,可以使用

// change the file name
Configure::write('SchedulerShell.storeFile', "scheduler_results.json");
// change the path (note the ending /)
Configure::write('SchedulerShell.storePath', "/path/to/save/");

防止同时运行相同的任务

默认情况下,SchedulerShell 将在运行不足 10 分钟时退出。您可以通过设置来调整此设置

// change the number of seconds to wait before running a parallel SchedulerShell; 0 = do not exit
Configure::write('SchedulerShell.processTimeout', 5*60);

其他说明/已知问题

  • 可选的 pass 参数尚未经过彻底测试
  • PHP 5.3.6 之前的版本仅用于 DateTime::modify() 函数的相对日期时间。因此,如果上一个 lastRun 时间是 05:02,则 "下一天 5:00" 的间隔可能不会运行。因此,此插件应仅在 PHP >= 5.3.6 上运行。