takielias/php-cron-scheduler-extended

PHP Cron Job Scheduler,受 peppeocchi/php-cron-scheduler 启发

1.2 2018-11-23 08:38 UTC

This package is auto-updated.

Last update: 2024-08-29 05:12:32 UTC


README

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 - 此方法接受由 mtdowling/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');

还有针对工作日的辅助函数(所有这些都接受可选的小时和分钟 - 默认为 00:00)

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

还有针对月份的辅助函数(所有这些都接受可选的日期、小时和分钟 - 默认为每月的 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_Transport自定义Swift_Mailer实例。您可以配置:

  • 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方法将cron作业的执行委托给一个真实的测试。

$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)