Tasks
Tasks let you run commands at specified intervals.
Overview
Typically, to automate tasks on a server you would use various “cron jobs” that runs things at specified intervals. You’d need to use the command line and remember strange syntaxes to get it working. How annoying. The Task Scheduler makes this simple.
Starting the Scheduler
To enable task scheduling, add the following Cron entry to your server:
* * * * * php /path/to/please schedule:run >> /dev/null 2>&1
This Cron will call the Statamic/Laravel command scheduler every minute and run any tasks that you have scheduled and runs them if they’re due, automatically. This single Cron entry is all it takes.
Instead of remembering the cron syntax, you can literally copy/paste the line above (and adjust the path to the please
file).
Generating
You can generate a tasks class file with a console command.
php please make:tasks AddonName
Defining Schedules
The tasks class consists of one method, schedule
, with one argument, $schedule
. From here, it’s 100% Laravel, so pop over to the Laravel docs for all the juicy details.
An Example Task
Here’s an example from a fictional CacheCleaner
addon that clears the cache once a week. Like a janitor, pulling pennies out of doors.
<?php
namespace Statamic\Addons\CacheCleaner;
use Statamic\Extend\Tasks;
use Illuminate\Console\Scheduling\Schedule;
class CacheCleanerTasks extends Tasks
{
/**
* Define the task schedule
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
*/
public function schedule(Schedule $schedule)
{
$schedule->command('cache:clear')->weekly();
}
}
If you haven’t already, you should learn how to create a command.