setono / cron-builder
Generate a crontab from a config directory
Installs: 25 004
Dependents: 2
Suggesters: 0
Security: 0
Stars: 2
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: >=8.1
- dragonmantank/cron-expression: ^3.0
- twig/twig: ^2.0 || ^3.0
Requires (Dev)
- infection/infection: ^0.27.11
- phpunit/phpunit: ^9.6
- psalm/plugin-phpunit: ^0.19.0
- setono/code-quality-pack: ^2.8.2
- symfony/finder: ^6.4 || ^7.0
README
Build your crontab from configuration files in your repository. The configuration files are written in PHP and can be placed anywhere in your repository.
Installation
composer require setono/cron-builder
Usage
The following two code snippets outlines the simplest usage of the cron builder.
1. Add your commands
<?php # etc/cronjobs/jobs.php declare(strict_types=1); use Setono\CronBuilder\Context; use Setono\CronBuilder\CronJob; return static function (Context $context): iterable { yield new CronJob('0 0 * * *', '/usr/bin/php {{ release_path }}/send-report.php {{ args|join(" ") }}', 'Run every day at midnight'); if ($context->get('env') === 'prod') { yield new CronJob('0 0 * * *', '/usr/bin/php {{ release_path }}/process.php {{ args|join(" ") }}'); } };
Notice the {{ release_path }}
and {{ args|join(" ") }}
placeholders.
These are placeholders that will be replaced with the values from the context array.
This is done using the Twig templating engine, which means
you can use all the features of Twig in your cronjob definitions.
2. Build the crontab
When your cronjobs are defined, you can output the crontab file:
<?php use Setono\CronBuilder\CronBuilder; use Symfony\Component\Finder\Finder; echo (new CronBuilder()) ->addFiles( (new Finder()) ->files() ->in(__DIR__ . '/etc/cronjobs') ->name('*.php') ) ->addContext('release_path', '/home/johndoe/public_html') ->addContext('env', 'prod') ->addContext('args', ['--verbose']) ->build() ;
This will output the following:
###> Automatically generated by Setono Cron Builder - DO NOT EDIT ###
0 0 * * * /usr/bin/php /home/johndoe/public_html/send-report.php --verbose # Run every day at midnight
0 0 * * * /usr/bin/php /home/johndoe/public_html/process.php --verbose
###< Automatically generated by Setono Cron Builder - DO NOT EDIT ###
You can save this in a file named crontab.txt
and add it to your crontab like this:
cat crontab.txt | crontab -