setono/cron-builder

Generate a crontab from a config directory

v1.0.0-alpha 2024-09-17 12:18 UTC

This package is auto-updated.

Last update: 2024-11-17 12:44:08 UTC


README

Latest Version Software License Build Status Coverage Status Mutation testing

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 -