adamz01h / php-cron-scheduler
PHP Cron Job Scheduler
Requires
- php: ^7.1
- dragonmantank/cron-expression: ^2.3
Requires (Dev)
- phpunit/phpunit: ~5.7
- satooshi/php-coveralls: ^1.0
- swiftmailer/swiftmailer: ~5.4 || ^6.0
Suggests
- swiftmailer/swiftmailer: Required to send the output of a job to email address/es (~5.4 || ^6.0).
This package is not auto-updated.
Last update: 2024-09-14 18:36:53 UTC
README
这是一个与框架无关的定时任务调度器,可以轻松集成到您的项目中或作为独立命令调度器运行。这个想法最初受到了Laravel Task Scheduling的启发。
通过Composer安装
推荐的方法是通过Composer安装php-cron-scheduler。请参阅入门指南了解如何下载和安装Composer。
下载/安装Composer后,运行
php composer.phar require peppeocchi/php-cron-scheduler
或将包添加到您的composer.json
{ "require": { "peppeocchi/php-cron-scheduler": "3.*" } }
版本V3需要php >= 7.1,对于7.1以下的php版本,请使用v2分支。
工作原理
在项目的根目录下创建一个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二进制文件
- 传递给脚本的参数(注意:您需要在php.ini中启用register_argc_argv才能使此功能正常工作(参考)。不必担心,默认情况下已启用,除非您故意禁用它或您的托管商默认禁用它,否则请忽略它。)
- 标识符
$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' );
您传递给数组的所有参数都将注入到您的函数中。例如
$scheduler->call( function ($firstName, $lastName) { return implode(' ', [$firstName, $lastName]); }, [ 'John', 'last_name' => 'Doe', // The keys are being ignored ], 'myCustomIdentifier' );
如果您想传递一个键=>值对,请将数组传递给参数数组中
$scheduler->call( function ($user, $role) { return implode(' ', [$user['first_name'], $user['last_name']]) . " has role: '{$role}'"; }, [ [ 'first_name' => 'John', 'last_name' => 'Doe', ], 'Admin' ], 'myCustomIdentifier' );
安排执行时间
有几个方法可以帮助您设置安排的执行时间。如果您没有调用任何此方法,则任务将每分钟运行一次(* * * * *)。
at
- 此方法接受dragonmantank/cron-expression支持的任何表达式$scheduler->php('script.php')->at('* * * * *');
everyMinute
- 每分钟运行一次。您可以可选地传递一个$minute
来指定任务每$minute
分钟运行一次。$scheduler->php('script.php')->everyMinute(); $scheduler->php('script.php')->everyMinute(5);
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);
还有额外的辅助程序用于月份(所有接受可选的日期、小时和分钟 - 默认为每月的第一天 00:00)
一月
二月
三月
四月
五月
六月
七月
八月
九月
十月
十一月
十二月
$scheduler->php('script.php')->january(); $scheduler->php('script.php')->december(25); $scheduler->php('script.php')->august(15, 20, 30);
您还可以指定一个运行作业的 date
。日期可以指定为字符串或 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
方法将 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);
作业失败
如果某个作业失败,你可以访问失败的作业列表和失败原因。
// get all failed jobs and select first $failedJob = $scheduler->getFailedJobs()[0]; // exception that occurred during job $exception = $failedJob->getException(); // job that failed $job = $failedJob->getJob();