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!
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.
Installation
To install it, we use Composer as usual:
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.
How Does it Work?
Instead of a installing cron jobs in a crontab file, we define them in one or several PHP files, by using the Crunz interface.
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:
* * * * * /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.
Task Files
Task files resemble crontab files. Just like crontab files, they can contain one or more tasks.
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.
By default, Crunz assumes all the task files reside in the tasks/
directory within the project's root directory.
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
Continue reading %Framework-Agnostic PHP Cronjobs Made Easy with Crunz!%
by Reza Lavaryan via SitePoint
No comments:
Post a Comment