Download the PHP package bakame/cron without Composer
On this page you can find all versions of the php package bakame/cron. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package cron
Bakame Cron Expression
NOTE This is a fork with a major rewrite of https://github.com/dragonmantank/cron-expression which is in turned a fork of the original https://github.com/mtdowling/cron-expression package.
To know more about cron expression your can look at the Unix documentation
Motivation
This package would not exist if the two listed packages were not around. While those packages are well known and used throughout the community I wanted to see if I could present an alternate way of dealing with cron expression.
The reason a fork was created instead of submitting PRs is because the changes to the public API are so important that it would have warranted multiples PR with some passing and other not. Hopefully, some ideas develop here can be re-use in the source packages.
System Requirements
You need PHP >= 8.1 but the latest stable version of PHP is recommended.
Installing
Using composer
Add the dependency to your project:
Going solo
You can also use Bakame\Cron without using Composer by downloading the library and:
- using any other PSR-4 compatible autoloader.
- using the bundle autoloader script as shown below:
require 'path/to/bakame/cron/repo/autoload.php';
use Bakame\Cron\Expression;
Expression::fromString('@daily')->toString(); //display '0 0 * * *'
where path/to/bakame/cron/repo represents the path where the library was extracted.
Usage
The following example illustrates some features of the package.
Calculating the running time
Instantiating the Scheduler Immutable Value Object
To determine the next running time for a CRON expression the package uses the Bakame\Cron\Scheduler class.
To work as expected this class requires:
- a CRON Expression ( as a string or as a
Expressionobject) - a timezone as a PHP
DateTimeZoneinstance or the timezone string name. - to know if the
startDateif eligible should be present in the results via aDatePresenceenum with two valuesDatePresence::INCLUDEDandDatePresence::EXCLUDED.
To ease instantiating the Scheduler, it comes bundle with two named constructors around timezone usage:
Scheduler::fromUTC: instantiate a scheduler using theUTCtimezone.Scheduler::fromSystemTimezone: instantiate a scheduler using the underlying system timezone
Both named constructors exclude by default the start date from the results.
The Scheduler public API methods accept:
string,DateTimeorDateTimeImmutableobject to represent a date object;string,DateIntervalobject to represent a date interval object;- positive integers or
0to represent recurrences or skipped occurrences;
Any other type will trigger an exception on usage. And for the methods that do returns
date object they will always return DateTimeImmutable objects with the Scheduler specified DateTimeZone.
Knowing if a CRON expression will run at a specific date
The Scheduler::isDue method can tell whether a specific CRON is due to run on a specific date.
Finding a running date for a CRON expression
The Scheduler::run method allows finding the following run date according to a specific date.
The Scheduler::run method allows specifying the number of matches to skip before calculating the next run.
The Scheduler::run method accepts negative number if you want to get a run date in the past.
Use the DatePresence enum on Scheduler instantiation or the appropriate configuration method
to allow Scheduler methods to include the start date in their result if eligible.
Scheduler::includeInitialDate(will include the start date if eligible)Scheduler::excludeInitialDate(will exclude the start date)
Because the Scheduler is an immutable object anytime a configuration settings is changed a new object is
returned instead of modifying the current object.
Iterating over multiple runs
You can iterate over a set of recurrent dates where the cron is supposed to run. The iteration can be done forward or backward depending on the endpoints provided. Like for other methods, the inclusion of the start date still depends on the scheduler configuration.
All listed methods hereafter returns a generator containing DateTimeImmutable objects.
Iterating forward using recurrences
The recurrences value should always be a positive integer or 0. Any negative value will trigger an exception.
Iterating backward using recurrences
The recurrences value should always be a positive integer or 0. Any negative value will trigger an exception.
Iterating using a starting date and an interval
The interval value should always be a positive DateInterval. Any negative value will trigger an exception.
Iterating using an end date and an interval
The interval value should always be a positive DateInterval. Any negative value will trigger an exception.
Iterating using a starting date and an end date
If the start date in greater than the end date the DateTimeImmutable objects will be returned backwards.
The Bakame\Cron\Scheduler object exposes the CRON expression using the Bakame\Cron\Expression immutable value object.
Handling CRON Expression
To work as intended, The Bakame\Cron\Expression resolves CRON Expression as they are described in the CRONTAB documentation
A CRON expression is a string representing the schedule for a particular command to execute. The parts of a CRON schedule are as follows:
* * * * *
- - - - -
| | | | |
| | | | |
| | | | +----- day of week (0 - 7) (Sunday=0 or 7)
| | | +---------- month (1 - 12)
| | +--------------- day of month (1 - 31)
| +-------------------- hour (0 - 23)
+------------------------- min (0 - 59)
The Expression value object also supports the following notations:
- L: stands for "last" and specifies the last day of the month;
- W: is used to specify the weekday (Monday-Friday) nearest the given day;
- #: allowed for the
dayOfWeekfield, and must be followed by a number between one and five; - range, split notations as well as the ? character;
Instantiation
By instantiating an Expression object you are validating its associated CRON Expression Field. Each CRON expression field
is validated via a CronField implementing object:
The package contains the following CRON expression Field value objects
MinuteFieldHourFieldDayOfMonthFieldMonthFieldDayOfWeekField
It is possible to use those CRON expression Field value objects to instantiate an Expression instance:
To ease instantiation the Expression object exposes easier to use named constructors.
Expression::fromString returns a new instance from a string.
Expression::fromFields returns a new instance from an associative array using the same index as the one returned by Expression::toFields.
*If a field is not provided it will be replaced by the `character.** **If unknown field are provided aSyntaxError` exception will be thrown.**
Formatting
The value object implements the JsonSerializable interface to ease interoperability and a toString method to
return the CRON expression string representation. As previously shown in the examples above, each CRON expression field
is represented by a public readonly property. Each of them also exposes a toString method
and implements the JsonSerializable interface too.
- The
Expression::toFieldsreturns an associative array of CRON expression field string representation;
Both methods produce the same JSON output string
Updates
Updating the CRON expression is done via its with* methods where the * is replaced by the corresponding CRON expression field name.
Those methods expect a CronField instance, a string or an integer.
Registering CRON Expression Aliases
The Expression class handles the following default aliases for CRON expression except @reboot.
| Alias | meaning | Expression constructor |
|---|---|---|
@reboot |
Run once, at startup | Not supported |
@yearly |
Run once a year | 0 0 1 1 * |
@annually |
Run once a year | 0 0 1 1 * |
@monthly |
Run once a month | 0 0 1 * * |
@weekly |
Run once a week | 0 0 * * 0 |
@daily |
Run once a day | 0 0 * * * |
@midnight |
Run once a day | 0 0 * * * |
@hourly |
Run once a hour | 0 * * * * |
It is possible to register more expressions via an alias name. Once registered it will be available when using the Expression object
but also when instantiating the Scheduler class with a CRON expression string.
An alias name needs to be a single word containing only ASCII letters and number and prefixed with the @ character. They should be
associated with any valid expression. Notice: Aliases are case insensitive
`
At any given time it is possible to:
- list all registered expressions and their associated aliases
- remove the already registered aliases except for the default ones listed in the table above.
`
Testing
The package has a :
- a PHPUnit test suite
- a coding style compliance test suite using PHP CS Fixer.
- a code analysis compliance test suite using PHPStan.
To run the tests, run the following command from the project folder once it is cloned from its source repository and the package is installed via composer.
Contributing
Contributions are welcome and will be fully credited. Please see CONDUCT for details.
Security
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
Changelog
Please see CHANGELOG for more information on what has changed recently.
Credits
License
The MIT License (MIT). Please see LICENSE for more information.