Crunz简化了与框架无关PHP Cronjobs!

tech2022-08-29  150

In this article, we’re going to learn about a relatively new job scheduling library named Crunz. Crunz is a framework-agnostic library inspired by Laravel’s Task Scheduler, but improved in many ways. Full disclosure: I’m the author and am welcoming contributions and comments on how to improve it further!

在本文中,我们将学习一个名为Crunz的相对较新的作业调度库。 Crunz是一个与框架无关的库,灵感来自Laravel的Task Scheduler ,但在许多方面进行了改进。 全面披露:我是作者,并欢迎就如何进一步改进做出贡献和提出评论!

Before getting started, you should have a firm grasp of cronjobs, so please read our in-depth walkthrough if you’re unfamiliar with how they work.

在开始之前,您应该对cronjob有所了解,因此,如果您不熟悉cronjob的工作原理,请阅读我们的深入演练 。

安装 (Installation)

To install it, we use Composer as usual:

要安装它,我们照常使用Composer:

composer require lavary/crunz

A command-line utility named crunz will be symlinked to vendor/bin of our project. This command-line utility provides a set of useful commands, which we’ll discuss shortly.

名为crunz的命令行实用程序将链接到我们项目的vendor/bin 。 此命令行实用程序提供了一组有用的命令,我们将在稍后讨论。

它是如何工作的? (How Does it Work?)

Instead of installing cron jobs in a crontab file, we define them in one or several PHP files, by using the Crunz interface.

无需在crontab文件中安装cron作业,而是通过使用Crunz接口在一个或几个PHP文件中定义它们。

Here’s a basic example:

这是一个基本示例:

<?php // tasks/backupTasks.php use Crunz\Schedule; $schedule = new Schedule(); $schedule->run('cp project project-bk') ->daily(); return $schedule;

To run the tasks, we install an ordinary cron job (a crontab entry) which runs every minute, and delegates the responsibility to Crunz’s event runner:

为了运行任务,我们安装了一个普通的cron作业(一个crontab条目),该作业每分钟运行一次 ,并将职责委派给Crunz的事件运行器:

* * * * * /project/vendor/bin/crunz schedule:run

The command schedule:run is responsible for collecting all the PHP task files and runs the tasks which are due.

命令schedule:run负责收集所有PHP任务文件并运行到期的任务。

任务文件 (Task Files)

Task files resemble crontab files. Just like crontab files, they can contain one or more tasks.

任务文件类似于crontab文件。 就像crontab文件一样,它们可以包含一个或多个任务。

To create a task file, we need to decide where we want to keep them. The location doesn’t matter as long as we let Crunz know the location. Normally, we create our task files in tasks/ within the project’s root directory. However, we can keep them outside of the project’s directory if there’s a reason for that.

要创建任务文件,我们需要确定要将文件保存在何处。 只要我们让Crunz知道位置,位置就没有关系。 通常,我们在项目根目录下的tasks/创建任务文件。 但是,如果有原因,我们可以将它们保留在项目目录之外。

By default, Crunz assumes all the task files reside in the tasks/ directory within the project’s root directory.

默认情况下,Crunz假定所有任务文件都位于项目根目录下的tasks/目录中。

There are two ways to specify the source directory: configuration file (more on this below) and as a parameter to the event runner command:

有两种方法可以指定源目录:配置文件(在下文中有更多说明)和作为事件运行程序命令的参数:

* * * * * /project/vendor/bin/crunz schedule:run /path/to/tasks/directory

创建一个简单的任务 (Creating a Simple Task)

Let’s create our first task.

让我们创建第一个任务。

<?php // tasks/FirstTasks.php use Crunz\Schedule; $schedule = new Schedule(); $schedule->run('cp project project-bk') ->daily() ->description('Create a backup of the project directory.'); // ... // IMPORTANT: You must return the schedule object return $schedule;

In the preceding code, first we make an instance of the Schedule class. run() specifies the command to be executed. daily() runs the command on a daily basis, and description() adds a description to the task (descriptions are useful for identifying the tasks in the log files).

在前面的代码中,首先我们创建Schedule类的实例。 run()指定要执行的命令 。 daily()运行一次命令, description()向任务添加描述(描述对于在日志文件中标识任务很有用)。

There are some conventions for creating a task file. The filename should end with Tasks.php unless we change this via the configuration settings. Additionally, we must return the instance of the Schedule class at the end of each file, otherwise, all the tasks inside the file will be skipped by the event runner.

创建任务文件有一些约定。 除非我们通过配置设置更改文件名,否则文件名应以Tasks.php结尾。 此外,我们必须在每个文件的末尾返回Schedule类的实例,否则,事件运行程序将跳过文件中的所有任务。

Since Crunz scans the tasks directory recursively, we can either put all the tasks in one file or across different files (or directories) based on their usage. This behavior helps us have a well organized tasks directory.

由于Crunz递归扫描任务目录,因此我们可以根据任务的使用将所有任务放在一个文件中,也可以将它们放在不同的文件(或目录)中。 此行为有助于我们拥有井井有条的任务目录。

命令 (The Command)

We can run any command or PHP closure by using run(). This method accepts two arguments: the command or closure to be executed, and the command options (as an associative array) if the first argument is a command.

我们可以使用run()运行任何命令或PHP闭包。 此方法接受两个参数: 要执行的命令或闭包 ,以及如果第一个参数是命令, 则命令选项 (作为关联数组)。

<?php use Crunz\Schedule; $schedule = new Schedule(); $schedule->run('/usr/bin/php backup.php', ['--destination' => 'path/to/destination']) ->everyMinute() ->description('Copying the project directory'); return $schedule;

In the above example, --destination is an option supported by the backup.php script.

在上面的示例中, --destination是backup.php脚本支持的选项。

关闭 (Closures)

Other than commands, it is also possible to schedule a PHP closure, by passing it to the run() method.

除了命令以外,还可以通过将PHP闭包传递给run()方法来安排它的关闭。

<?php use Crunz\Schedule; $schedule = new Schedule(); $x = 'Some data'; $schedule->run(function() use ($x) { echo 'Doing some cool stuff in here with ' . $x; }) ->everyMinute() ->description('Cool stuff'); return $schedule;

If there’s a PHP error on any level, it will be caught, logged and reported.

如果任何级别都有PHP错误,它将被捕获,记录和报告。

更改目录 (Changing Directories)

It is also possible to change the current working directory before running a task – by using the in() method:

通过运行in()方法,还可以在运行任务之前更改当前的工作目录:

<?php // ... $schedule->run('./deploy.sh') ->in('/home') ->daily(); // ... return $schedule;

执行频率 (Frequency of Execution)

There are a variety of ways to specify when and how often a task should run. We can combine these methods to get our desired frequencies.

有多种方法可以指定任务的运行时间和频率 。 我们可以结合使用这些方法来获得所需的频率。

时间单位 (Units of Time)

Frequency methods usually end with ly, as in hourly(), daily(), weekly(), monthly(), quarterly(), and yearly() .

频率方法通常以ly结尾,如hourly() , daily() , weekly() , monthly() , quarterly()和yearly() 。

<?php // ... $schedule->run('/usr/bin/php backup.php') ->daily(); // ...

The above task will run daily at midnight.

以上任务将每天在午夜运行。

Here’s another one, which runs on the first day of each month.

这是另一个,在每个月的第一天运行。

<?php // ... $schedule->run('/usr/bin/php email.php') ->monthly(); // ...

All the events scheduled with this set of methods happen at the beginning of that time unit. For example weekly() will run the event on Sundays, and monthly() will run it on the first day of each month.

用这组方法安排的所有事件都在该时间单位的开始发生。 例如, weekly()将在星期日运行事件, monthly()将在monthly()的第一天运行事件。

动态方法 (Dynamic Methods)

Dynamic methods give us a wide variety of frequency options on the fly. We just need to follow this pattern:

动态方法为我们提供了动态的多种频率选择。 我们只需要遵循以下模式:

every[NumberInCamelCaseWords]Minute|Hour|Day|Months?

The method should start with the word every, followed by a number in camel-case words, ending with one of these units of time: minute, hour, day, and month.

该方法应以单词every开头,然后以驼峰大小写的单词开头,然后以以下时间单位之一结束: 分钟,小时,天和月 。

The s at the end is optional and it’s just used for grammar’s sake.

最后的s是可选的,仅出于语法目的而使用。

That said, the following methods are valid:

也就是说,以下方法有效:

everyFiveMinutes()

everyFiveMinutes()

everyMinute()

everyMinute()

everyTwelveHours()

everyTwelveHours()

everyMonth()

everyMonth()

everySixMonths()

everySixMonths()

everyFifteenDays()

everyFifteenDays()

everyFiveHundredThirtySevenMinutes()

everyFiveHundredThirtySevenMinutes()

everyThreeThousandAndFiveHundredFiftyNineMinutes()

everyThreeThousandAndFiveHundredFiftyNineMinutes()

This is how we use it in a task file:

这是我们在任务文件中使用它的方式:

<?php // ... $schedule->run('/usr/bin/php email.php') ->everyTenDays(); $schedule->run('/usr/bin/php some_other_stuff.php') ->everyThirteenMinutes(); // ... return $schedule;

在特定时间运行事件 (Running Events at a Certain Time)

To schedule one-off tasks, we can use the on() method like this:

要安排一次性任务,我们可以使用on()方法,如下所示:

<?php // ... $schedule->run('/usr/bin/php email.php') ->on('13:30 2016-03-01'); // ...

The above the task will run on the first of March 2016 at 01:30 pm.

以上任务将于2016年3月1日下午01:30运行。

on() accepts any date format parsed by PHP’s strtotime function.

on()接受PHP的strtotime函数解析的任何日期格式。

To specify only the time, we use at():

为了只指定时间,我们使用at() :

<?php // ... $schedule->run('/usr/bin/php script.php') ->daily() ->at('13:30'); // ...

We can use dailyAt() to get the same result:

我们可以使用dailyAt()获得相同的结果:

<?php // ... $schedule->run('/usr/bin/php script.php') ->dailyAt('13:30'); // ...

If we only pass time to on(), it has the same effect as using at()

如果仅将时间传递给on() ,则其效果与使用at()

<?php // ... $schedule->run('/usr/bin/php email.php') ->mondays() ->on('13:30'); // is the sames as $schedule->run('/usr/bin/php email.php') ->mondays() ->at('13:30'); // ...

平日 (Weekdays)

Crunz also provides a set of methods which specify a certain day in the week. These methods have been designed to be used as a constraint and should not be used alone. The reason is that weekday methods just modify the Day of Week field of the cron job expression.

Crunz还提供了一组指定一周中特定日期的方法。 这些方法已设计为用作约束,不应单独使用。 原因是平日方法仅修改了cron作业表达式Day of Week字段。

Consider the following example:

考虑以下示例:

<?php // Cron equivalent: * * * * 1 $schedule->run('/usr/bin/php email.php') ->mondays();

At first glance, the task seems to run every Monday, but since it only modifies the “day of week” field of the cron job expression, the task runs every minute on Mondays.

乍看起来,该任务似乎在每个星期一运行,但是由于它仅修改cron作业表达式的“星期几”字段,因此该任务在星期一每分钟运行一次 。

This is the correct way of using weekday methods:

这是使用工作日方法的正确方法:

<?php // ... $schedule->run('/usr/bin/php email.php') ->everyThreeHours() ->mondays(); // ...

In the above task, we use mondays() as a constraint to run the task every three hours on Mondays.

在上述任务中,我们使用mondays()作为约束, 在星期一每三个小时运行一次任务。

设置单个字段 (Setting Individual Fields)

Crunz’s methods are not limited to the ready-made methods explained. We can also set individual fields to compose our custom frequencies. These methods either accept an array of values, or list arguments separated by commas:

Crunz的方法不仅限于已说明的现成方法。 我们还可以设置各个字段来组成我们的自定义频率。 这些方法要么接受值数组,要么列出用逗号分隔的参数:

<?php // ... $schedule->run('/usr/bin/php email.php') ->minute(['1-30', 45, 55]) ->hour('1-5', 7, 8) ->dayOfMonth(12, 15) ->month(1);

Or:

要么:

<?php // ... $schedule->run('/usr/bin/php email.php') ->minute('30') ->hour('13') ->month([1,2]) ->dayofWeek('Mon', 'Fri', 'Sat'); // ...

经典方式 (The Classic Way)

We can also do the scheduling the old way, just like we do in a crontab file:

我们也可以使用旧的方式进行调度,就像在crontab文件中一样:

<?php $schedule->run('/usr/bin/php email.php') ->cron('30 12 * 5-6,9 Mon,Fri');

任务寿命 (Task Lifetime)

In a crontab entry, we can not easily specify a task’s lifetime (the period during which the task is active). With Crunz, it’s possible:

在crontab条目中,我们无法轻松指定任务的生存期(任务处于活动状态的时间段)。 使用Crunz,有可能:

<?php // $schedule->run('/usr/bin/php email.php') ->everyFiveMinutes() ->from('12:30 2016-03-04') ->to('04:55 2016-03-10'); //

Alternatively, we can use the between() method to get the same result:

另外,我们可以使用between()方法获得相同的结果:

<?php // $schedule->run('/usr/bin/php email.php') ->everyFiveMinutes() ->between('12:30 2016-03-04', '04:55 2016-03-10'); //

If we don’t specify the date portion, the task will be active every day but only within the specified duration:

如果我们不指定日期部分,则该任务每天都将处于活动状态,但仅在指定的持续时间内:

<?php // $schedule->run('/usr/bin/php email.php') ->everyFiveMinutes() ->between('12:30', '04:55'); //

The above task runs every five minutes between 12:30 pm and 4:55 pm every day.

上面的任务每天在每天 12:30 pm和4:55 pm之间每五分钟运行一次 。

运行条件 (Running Conditions)

Another thing that we cannot do very easily in a traditional crontab file is make conditions for running the tasks. Enter when() and skip() methods.

在传统的crontab文件中,我们不能轻易完成的另一件事是为运行任务创造条件。 输入when()和skip()方法。

Consider the following code:

考虑以下代码:

<?php // $schedule->run('/usr/bin/php email.php') ->everyFiveMinutes() ->between('12:30 2016-03-04', '04:55 2016-03-10') ->when(function() { if ($some_condition_here) { return true; } }); //

when() accepts a callback which must return TRUE for the task to run. This can be really useful when we need to check our resources before performing a resource-hungry task, for example. We can also skip a task under certain conditions by using the skip() method. If the passed callback returns TRUE, the task will be skipped.

when()接受一个回调,该回调必须返回TRUE才能运行任务。 例如,当我们需要在执行资源紧张的任务之前检查资源时,这将非常有用。 我们还可以通过使用skip()方法在某些条件下跳过任务。 如果传递的回调返回TRUE ,则将跳过任务。

<?php // $schedule->run('/usr/bin/php email.php') ->everyFiveMinutes() ->between('12:30 2016-03-04', '04:55 2016-03-10') ->skip(function() { if ($some_condition_here) { return true; } }); //

We can use these methods multiple times for a single task. They are evaluated sequentially.

我们可以使用这些方法多次单个任务。 依序评估它们。

组态 (Configuration)

There are a few configuration options provided in YAML format. It is highly recommended to have your own copy of the configuration file, instead modifying the original one.

YAML格式提供了一些配置选项。 强烈建议您拥有自己的配置文件副本,而不要修改原始副本。

To create a copy of the configuration file, first we need to publish the configuration file:

要创建配置文件的副本,首先我们需要发布配置文件:

crunz publish:config The configuration file was generated successfully

As a result, a copy of the configuration file will be created within our project’s root directory.

结果,将在我们项目的根目录中创建配置文件的副本。

The configuration file looks like this:

配置文件如下所示:

# Crunz Configuration Settings # This option defines where the task files and # directories reside. # The path is relative to the project's root directory, # where the Crunz is installed (Trailing slashes will be ignored). source: tasks # The suffix is meant to target the task files inside the ":source" directory. # Please note if you change this value, you need # to make sure all the existing tasks files are renamed accordingly. suffix: Tasks.php # By default the errors are not logged by Crunz # You may set the value to true for logging the errors log_errors: false # This is the absolute path to the errors' log file # You need to make sure you have the required permission to write to this file though. errors_log_file: # By default the output is not logged as they are redirected to the # null output. # Set this to true if you want to keep the outputs log_output: false # This is the absolute path to the global output log file # The events which have dedicated log files (defined with them), won't be # logged to this file though. output_log_file: # This option determines whether the output should be emailed or not. email_output: false # This option determines whether the error messages should be emailed or not. email_errors: false # Global Swift Mailer settings # mailer: # Possible values: smtp, mail, and sendmail transport: smtp recipients: sender_name: sender_email: # SMTP settings # smtp: host: port: username: password: encryption:

Each time we run Crunz commands, it will look into the project’s root directory to see if there’s a user-modified configuration file. If the configuration file doesn’t exist, it will use the default one.

每次我们运行Crunz命令时,它都会查看项目的根目录,以查看是否存在用户修改的配置文件。 如果配置文件不存在,它将使用默认文件。

并行性和锁定机制 (Parallelism and the Locking Mechanism)

Crunz runs the scheduled events in parallel (in separate processes), so all the events which have the same frequency of execution will run at the same time, asynchronously. To achieve this, Crunz utilizes symfony/Process for running the tasks in sub-processes.

Crunz并行运行计划的事件(在单独的进程中),因此,具有相同执行频率的所有事件将异步地同时运行。 为此,Crunz利用symfony / Process在子流程中运行任务。

If the execution of a task lasts until the next interval or even beyond that, we say that the same instances of a task are overlapping. In some cases, this is a not a problem, but they are times when these tasks are modifying the database data or files, which might cause unexpected behavior, or even data loss.

如果任务的执行持续到下一个时间间隔或更晚,则我们将任务的相同实例重叠。 在某些情况下,这不是问题,但是有时这些任务正在修改数据库数据或文件,这可能会导致意外行为,甚至数据丢失。

To prevent critical tasks from overlapping, Crunz provides a locking mechanism through preventOverlapping() which ensures no task runs if the previous instance is already running. Behind the scenes, Crunz creates a special file for each task, storing the process ID of the last running instance. Every time a task is about to run, it reads the process ID of the respective task, and checks if it’s still running. If it’s not, it’s time to run a new instance.

为了防止关键任务重叠,Crunz通过preventOverlapping()提供了一种锁定机制,该机制可以确保如果先前的实例已经在运行,则不会运行任何任务。 在幕后,Crunz为每个任务创建一个特殊文件,其中存储了最后一个运行实例的进程ID。 每当任务即将运行时,它都会读取相应任务的进程ID,并检查它是否仍在运行。 如果不是,那么该运行一个新实例了。

<?php // $schedule->run('/usr/bin/php email.php') ->everyFiveMinutes() ->preventOverlapping(); //

保持输出 (Keeping the Output)

Cron jobs usually have output, which is normally emailed to the owner of the crontab file, or the user or users set by the MAILTO environment variable in the crontab file.

Cron作业通常具有输出,通常通过电子邮件发送给crontab文件的所有者,或通过crontab文件中的MAILTO环境变量设置的一个或多个用户。

We can also redirect the standard output to a physical file using the >> operator:

我们还可以使用>>运算符将标准输出重定向到物理文件:

* * * * * /command/to/run >> /var/log/crons/cron.log

This has been automated in Crunz. To automatically send each event’s output to a log file, we can set log_output and output_log_file in the configuration file like this:

这在Crunz中已自动化。 要将每个事件的输出自动发送到日志文件,我们可以在配置文件中设置log_output和output_log_file ,如下所示:

# Configuration settings ## ... log_output: true output_log_file: /var/log/crunz.log ## ...

This will send the event’s output (if executed successfully) to /var/log/crunz.log. However, we need to make sure we are permitted to write to the respective directory.

这会将事件的输出(如果成功执行)发送到/var/log/crunz.log 。 但是,我们需要确保允许我们写入相应的目录。

If we need to log the output on a per-event basis, we can use appendOutputTo() or sendOutputTo() methods like this:

如果需要按事件记录输出,则可以使用appendOutputTo()或sendOutputTo()方法,如下所示:

<?php // $schedule->run('/usr/bin/php email.php') ->everyFiveMinutes() ->appendOutputTo('/var/log/crunz/emails.log'); //

Method appendOutputTo() appends the output to the specified file. To override the log file with new data after each run, we use saveOutputTo().

方法appendOutputTo() 将输出追加到指定的文件。 为了在每次运行后用新数据覆盖日志文件,我们使用saveOutputTo() 。

It is also possible to send the output as emails to a group of recipients by setting email_output and mailer settings in the configuration file.

通过在配置文件中设置email_output和mailer设置,也可以将输出作为电子邮件发送给一组收件人。

错误处理 (Error Handling)

Error handling is quite easy with Crunz. We can configure Crunz to log the error or notify us via email. Additionally, we can define several callbacks to be invoked in case of an error.

使用Crunz可以很容易地处理错误。 我们可以配置Crunz记录错误或通过电子邮件通知我们。 另外,我们可以定义几个发生错误时要调用的回调。

To log the possible errors during each run, we can use the log_error and error_log_file settings in the configuration file as below:

要记录每次运行期间可能出现的错误,我们可以使用配置文件中的log_error和error_log_file设置,如下所示:

# Configuration settings # ... log_errors: true errors_log_file: /var/log/error.log # ...

As a result, if the execution of an event is unsuccessful for some reason, the error message is appended to the specified error log file. Each entry provides useful information including the time it happened, the event’s description, the executed command which caused the error, and the error message itself.

结果,如果由于某种原因无法成功执行事件,则错误消息将附加到指定的错误日志文件中。 每个条目都提供有用的信息,包括事件发生的时间,事件的描述,导致错误的已执行命令以及错误消息本身。

Just like the event’s output, it is also possible to send the errors via email to a group of recipients – by setting email_error and mailer settings in the configuration file.

就像事件的输出一样,也可以通过在配置文件中设置email_error和mailer设置,通过电子邮件将错误发​​送给一组收件人。

错误回调 (Error Callbacks)

We can set as many callbacks as needed to run in case of an error. They will be invoked sequentially:

我们可以根据需要设置尽可能多的回调以在发生错误时运行。 它们将被顺序调用:

<?php use Crunz\Schedule; $schedule = new Schedule(); $schedule->add('command/to/run') ->everyFiveMinutes(); $schedule ->onError(function(){ // Send mail }) ->onError(function(){ // Do something else }); return $schedule;

预处理和后处理挂钩 (Pre-Process and Post-Process Hooks)

There are times when we want to do some operations before and after an event. This is possible by attaching pre-process and post-process callbacks to the respective event or schedule object by using before() and after() methods, passing a callback function to them.

有时候,我们想在事件发生之前和之后进行一些操作。 这可以通过使用before()和after()方法将预处理和后处理回调附加到相应的事件或计划对象,并将回调函数传递给它们来实现。

We can have pre-process and post-process callbacks on both event and schedule levels. The schedule-level pre-process callbacks will be invoked before any events (in the schedule object) have started. The schedule-level post-process callbacks will be invoked after all the events have been completed – whether successfully or with problems.

我们可以在事件和计划级别都具有预处理和后处理回调。 计划级别的预处理回调将在任何事件(在计划对象中)开始之前被调用。 在所有事件(无论成功还是有问题)都完成之后,将调用计划级别的后处理回调。

<?php // ... $schedule = new Schedule(); $schedule->run('/usr/bin/php email.php') ->everyFiveMinutes() ->before(function() { // Do something before the task runs }) ->before(function() { // Do something else }) ->after(function() { // After the task is run }); $schedule ->before(function () { // Do something before all events }) ->after(function () { // Do something after all events are finished } ->before(function () { // Do something before all events }); // ...

We can use these methods as many times as we need by chaining them. Event-based post-execution callbacks are only invoked if the execution of the event was successful.

通过链接它们,我们可以根据需要多次使用这些方法。 仅在事件执行成功时才调用基于事件的执行后回调。

其他有用的命令 (Other Useful Commands)

We’ve already used a few crunz commands like schedule:run and publish:config.

我们已经使用了一些crunz命令,例如schedule:run和publish:config 。

To see all the valid options and arguments of crunz, we can run the following command:

要查看crunz所有有效选项和参数,我们可以运行以下命令:

vendor/bin/crunz --help

列出任务 (Listing Tasks)

One of these commands is crunz schedule:list, which lists the defined tasks (in collected *.Tasks.php files) in a tabular format.

这些命令之一是crunz schedule:list ,它以表格形式列出已定义的任务(以收集的*.Tasks.php文件形式)。

vendor/bin/crunz schedule:list +---+---------------+-------------+--------------------+ | # | Task | Expression | Command to Run | +---+---------------+-------------+--------------------+ | 1 | Sample Task | * * * * 1 * | command/to/execute | +---+---------------+-------------+--------------------+

产生任务 (Generating Tasks)

There’s also a useful command make:task, which generates a task file skeleton with all the defaults, so one doesn’t have to write them from scratch.

还有一个有用的命令make:task ,它会生成一个具有所有默认设置的任务文件框架,因此不必从头开始编写它们。

For example, to create a task which runs /var/www/script.php every hour on Mondays, we run the following command:

例如,要创建一个在星期一每小时运行/var/www/script.php的任务,我们运行以下命令:

vendor/bin/crunz make:task exampleOne --run scripts.php --in /var/www --frequency everyHour --constraint mondays Where do you want to save the file? (Press enter for the current directory)

As a result, the event is defined in exampleOneTasks.php within the specified tasks directory.

结果,该事件在指定的task目录中的exampleOneTasks.php中定义。

To see if the event has been created successfully, we can list the events:

要查看事件是否已成功创建,我们可以列出事件:

crunz schedule:list +---+------------------+-------------+----------------+ | # | Task | Expression | Command to Run | +---+------------------+-------------+----------------+ | 1 | Task description | 0 * * * 1 * | scripts.php | +---+------------------+-------------+----------------+

To see all the options of make:task with all the defaults, we run it with help:

要查看带有所有默认设置的make:task的所有选项,我们在help运行它:

vendor/bin/crunz make:task --help

在基于Web的界面上使用Crunz (Using Crunz with a Web-based Interface)

Creating a web-based interface for Crunz is quite easy. We’ll just need to put the events’ properties inside a database table. Then, we can fetch all the records through an API. Finally, we iterate over the fetched records, creating the event objects. Whether an event has been created dynamically or statically, Crunz will run it as long as it is located in a valid task file.

为Crunz创建基于Web的界面非常容易。 我们只需要将事件的属性放在数据库表中即可。 然后,我们可以通过API获取所有记录。 最后,我们遍历提取的记录,创建事件对象。 无论事件是动态创建还是静态创建,只要事件位于有效任务文件中,Crunz都将运行它。

If you need to try something ready-made and expand it based on your requirements, you may use this web interface created with Laravel: lavary/crunz-ui. You can read the installation instructions in the package’s README.md file. In order to let users implement their own authentication mechanism, this web-based interface does not provide any authentication system out of the box.

如果您需要尝试现成的东西并根据需要进行扩展,则可以使用通过Laravel创建的以下Web界面: lavary / crunz-ui 。 您可以阅读软件包的README.md文件中的安装说明。 为了让用户实现自己的身份验证机制,此基于Web的界面不提供任何现成的身份验证系统。

结论 (Conclusion)

By having our tasks in the code, we can bring them under version control, so other developers can add or modify items without having to access the server.

通过将我们的任务包含在代码中,我们可以将它们置于版本控制之下,以便其他开发人员无需访问服务器即可添加或修改项目。

That way, we can control the tasks in any way we need, and to stop all of them permanently at once, we simply uninstall the master cron job.

这样,我们可以以所需的任何方式控制任务,并且要立即永久停止所有任务,我们只需卸载主cron作业即可。

If you have a questions or comments, please post them below and we’ll do our best to reply in a timely manner – and don’t hesitate to throw some suggestions and opinions about the package itself in there!

如果您有任何疑问或意见,请在下面将其发布,我们将尽力及时答复-并在其中毫不犹豫地对包装本身提出一些建议和意见!

翻译自: https://www.sitepoint.com/framework-agnostic-php-cronjobs-made-easy-with-crunz/

相关资源:jdk-8u281-windows-x64.exe
最新回复(0)