debuss/php-cron-scheduler

PHP Cron 作业调度器

2.4.1 2019-04-05 06:07 UTC

README

注意:此分支是为了使用拉取请求 #48 而制作的,因为它尚未正式发布。
已删除required-devs,以保持简单。

Latest Stable Version License Build Status Coverage Status StyleCI Total Downloads

这是一个框架无关的cron作业调度器,可以轻松集成到您的项目中或作为独立的命令调度器运行。最初的想法灵感来源于Laravel任务调度

通过Composer安装

推荐的方式是通过Composer安装php-cron-scheduler。请参阅入门了解如何下载和安装Composer。

下载/安装Composer后,运行

php composer.phar require peppeocchi/php-cron-scheduler

或将包添加到您的composer.json

{
    "require": {
        "peppeocchi/php-cron-scheduler": "2.*"
    }
}

工作原理

在您的项目根目录中创建一个名为scheduler.php的文件,并包含以下内容。

<?php require_once __DIR__.'/vendor/autoload.php';

use GO\Scheduler;

// Create a new scheduler
$scheduler = new Scheduler();

// ... configure the scheduled jobs (see below) ...

// Let the scheduler execute jobs which are due.
$scheduler->run();

然后向您的crontab添加一个新的条目,每分钟运行一次scheduler.php

* * * * * path/to/phpbin path/to/scheduler.php 1>> /dev/null 2>&1

就这样!您的调度器已经启动并运行,现在您可以添加作业而不用担心crontab了。

安排作业

默认情况下,所有作业都将尝试在后台运行。PHP脚本和原始命令默认在后台运行,而函数始终在前景运行。您可以通过调用inForeground()方法强制命令在前台运行。需要将输出发送到电子邮件的作业将在前台运行

安排PHP脚本

$scheduler->php('path/to/my/script.php');

php方法接受4个参数

  • 您的PHP脚本的路径
  • 要使用的PHP二进制文件
  • 要传递给脚本的参数
  • 标识符
$scheduler->php(
    'path/to/my/script.php', // The script to execute
    'path/to/my/custom/bin/php', // The PHP bin
    [
        '-c' => 'ignore',
        '--merge' => null,
    ],
    'myCustomIdentifier'
);

安排原始命令

$scheduler->raw('ps aux | grep httpd');

raw方法接受3个参数

  • 您的命令
  • 要传递给命令的参数
  • 标识符
$scheduler->raw(
    'mycommand | myOtherCommand',
    [
        '-v' => '6',
        '--silent' => null,
    ],
    'myCustomIdentifier'
);

安排函数

$scheduler->call(function () {
    return true;
});

call方法接受3个参数

  • 您的函数
  • 要传递给函数的参数
  • 标识符
$scheduler->call(
    function ($args) {
        return $args['user'];
    },
    [
        'user' => $user,
    ],
    'myCustomIdentifier'
);

安排执行时间

有几个方法可以帮助您设置安排的执行时间。如果您没有调用任何此方法,作业将每分钟运行一次 (* * * * *)。

  • at - 此方法接受dragonmantank/cron-expression支持的任何表达式
    $scheduler->php('script.php')->at('* * * * *');
  • everyMinute - 每分钟运行一次
    $scheduler->php('script.php')->everyMinute();
  • hourly - 每小时运行一次。您可以可选地传递要运行的$minute,默认情况下它将在每小时的'00'分运行。
    $scheduler->php('script.php')->hourly();
    $scheduler->php('script.php')->hourly(53);
  • daily - 每天运行一次。您可以可选地传递$hour$minute以获得更细粒度的控制(或字符串hour:minute
    $scheduler->php('script.php')->daily();
    $scheduler->php('script.php')->daily(22, 03);
    $scheduler->php('script.php')->daily('22:03');

对于工作日(所有这些都接受可选的hour和minute - 默认为00:00)有额外的助手

  • 星期天
  • 星期一
  • 星期二
  • 星期三
  • 星期四
  • 星期五
  • 星期六
$scheduler->php('script.php')->saturday();
$scheduler->php('script.php')->friday(18);
$scheduler->php('script.php')->sunday(12, 30);

对于月份(所有这些都接受可选的day、hour和minute - 默认为每月的1号00:00)有额外的助手

  • 一月
  • 二月
  • 三月
  • 四月
  • 五月
  • 六月
  • 七月
  • 八月
  • 九月
  • 十月
  • 十一月
  • 十二月
$scheduler->php('script.php')->january();
$scheduler->php('script.php')->december(25);
$scheduler->php('script.php')->august(15, 20, 30);

您还可以指定一个 日期,以便工作在何时运行。日期可以指定为字符串或 DateTime 实例。在两种情况下,您可以只指定日期(例如,2018-01-01)或同时指定时间(例如,2018-01-01 10:30)。如果您不指定时间,它将在该日期的 00:00 运行。如果您以“非标准”格式提供日期,强烈建议传递 DateTime 实例。如果您在未指定时间的情况下使用 createFromFormat,并且希望默认为 00:00,只需确保在日期格式中添加一个 !,否则时间将是当前时间。 了解更多

$scheduler->php('script.php')->date('2018-01-01 12:20');
$scheduler->php('script.php')->date(new DateTime('2018-01-01'));
$scheduler->php('script.php')->date(DateTime::createFromFormat('!d/m Y', '01/01 2018'));

将输出发送到文件/多个文件

您可以为脚本/命令/函数执行输出指定一个或多个文件。

$scheduler->php('script.php')->output([
    'my_file1.log', 'my_file2.log'
]);

// The scheduler catches both stdout and function return and send
// those values to the output file
$scheduler->call(function () {
    echo "Hello";

    return " world!";
})->output('my_file.log');

将输出发送到电子邮件/多个电子邮件

您可以为脚本/命令/函数执行输出指定一个或多个电子邮件地址。为了发送电子邮件,需要先将作业的输出发送到一个文件。实际上,文件将附加到您的电子邮件地址。为了实现这一点,您需要安装 swiftmailer/swiftmailer

$scheduler->php('script.php')->output([
    // If you specify multiple files, both will be attached to the email
    'my_file1.log', 'my_file2.log'
])->email([
    'someemail@mail.com' => 'My custom name',
    'someotheremail@mail.com'
]);

您可以选择使用自定义的 Swift_Mailer 实例与自定义的 Swift_Transport。您可以配置

  • subject - 发送电子邮件的主题
  • from - 设置为发送者的电子邮件地址
  • body - 电子邮件正文
  • transport - 要使用的传输。例如,如果您想使用您的 Gmail 账户或任何其他 SMTP 账户。该值应该是 Swift_Tranport 实例
  • ignore_empty_output - 如果设置为 true,则没有输出的作业不会触发任何电子邮件。

可以在创建调度器时为所有调度命令“全局”设置配置。

$scheduler = new Scheduler([
    'email' => [
        'subject' => 'Visitors count',
        'from' => 'cron@email.com',
        'body' => 'This is the daily visitors count',
        'transport' => Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
            ->setUsername('username')
            ->setPassword('password'),
        'ignore_empty_output' => false,
    ]
]);

或根据每个作业分别设置。

$scheduler = new Scheduler();

$scheduler->php('myscript.php')->configure([
    'email' => [
        'subject' => 'Visitors count',
    ]
]);

$scheduler->php('my_other_script.php')->configure([
    'email' => [
        'subject' => 'Page views count',
    ]
]);

安排条件执行

有时您可能不仅希望在执行时间到来时执行计划,而且还需要根据其他条件执行。

您可以使用 when 方法将 cronjob 的执行委托给一个布尔测试。

$scheduler->php('script.php')->when(function () {
    // The job will run (if due) only when
    // this function returns true
    return true;
});

安排执行顺序

即将运行的作业将根据它们的执行进行排序:可以 在后台 运行的作业将 首先 执行。

安排重叠

为了防止在先前的执行仍在进行时执行计划,请使用 onlyOne 方法。为了避免重叠,调度器需要创建 锁文件。默认情况下,它将使用用于临时文件的目录路径。

您可以在创建新的调度器实例时全局指定自定义目录路径。

$scheduler = new Scheduler([
    'tempDir' => 'path/to/my/tmp/dir'
]);

$scheduler->php('script.php')->onlyOne();

或者您可以在每个作业的基础上定义目录路径。

$scheduler = new Scheduler();

// This will use the default directory path
$scheduler->php('script.php')->onlyOne();

$scheduler->php('script.php')->onlyOne('path/to/my/tmp/dir');
$scheduler->php('other_script.php')->onlyOne('path/to/my/other/tmp/dir');

在某些情况下,您可能希望即使作业重叠也要运行作业。例如,如果上次执行超过 5 分钟。您可以传递一个函数作为第二个参数,注入上次执行时间。作业将不会运行,直到此函数返回 false。如果它返回 true,则即使重叠,作业也会运行。

$scheduler->php('script.php')->onlyOne(null, function ($lastExecutionTime) {
    return (time() - $lastExecutionTime) > (60 * 5);
});

作业执行前

在某些情况下,您可能希望在执行之前运行一些代码,如果作业即将运行。例如,您可能希望添加日志条目、ping URL 或其他任何内容。为此,您可以像下面的示例那样调用 before

// $logger here is your own implementation
$scheduler->php('script.php')->before(function () use ($logger) {
    $logger->info("script.php started at " . time());
});

作业执行后

有时您可能希望在作业运行后执行某些操作。`then` 方法提供您在作业执行后执行任何操作的灵活性。作业的输出将被注入到这个函数中。例如,您可能想将条目添加到日志中、ping一个URL等... 默认情况下,作业将强制在前景运行(因为输出被注入到函数中),如果您不需要输出,您可以将`true`作为第二个参数传递,以允许在后台执行(在这种情况下,`$output`将为空)。

// $logger and $messenger here are your own implementation
$scheduler->php('script.php')->then(function ($output) use ($logger, $messenger) {
    $logger->info($output);

    $messenger->ping('myurl.com', $output);
});

$scheduler->php('script.php')->then(function ($output) use ($logger) {
    $logger->info('Job executed!');
}, true);

一起使用 "before" 和 "then" 方法

// $logger here is your own implementation
$scheduler->php('script.php')
    ->before(function () use ($logger) {
        $logger->info("script.php started at " . time());
    })
    ->then(function ($output) use ($logger) {
        $logger->info("script.php completed at " . time(), [
            'output' => $output,
        ]);
    });

多个调度器运行

在某些情况下,您可能需要在同一脚本中多次运行调度器。尽管这不是一个常见的用例,但以下方法将允许您重用相同的调度器实例。

# some code
$scheduler->run();
# ...

// Reset the scheduler after a previous run
$scheduler->resetRun()
          ->run(); // now we can run it again

如果您在每次运行时重用相同的调度器实例并使用不同的作业(例如,来自外部源 - 数据库、文件等),则另一个实用的方法是清除当前的计划作业。

$scheduler->clearJobs();

$jobsFromDb = $db->query(/*...*/);
foreach ($jobsFromDb as $job) {
    $scheduler->php($job->script)->at($job->schedule);
}

$scheduler->resetRun()
          ->run();

模拟调度器运行时间

在运行调度器时,您可能需要传递一个`DateTime`来模拟调度器运行时间。此功能的理由请参见这里

// ...
$fakeRunTime = new DateTime('2017-09-13 00:00:00');
$scheduler->run($fakeRunTime);

许可

MIT 许可证 (MIT)