php - Adding custom methods to Laravel 5 scheduler -
i'm wondering best way add things weekends available schedule constraints:
illuminate\console\scheduling\event.php public function weekdays() { return $this->spliceintoposition(5, '1-5'); }
and logical opposite:
public function weekends() { return $this->days(array( '0','6')); }
where include these things they're not overwritten framework update?
first of all, if missing weekends() method, can achieve calling days(6,7) on event.
if need add more logic scheduler, please go on reading.
i had @ code , while laravel doesn't offer way extend scheduler, , scheduled events, additional methoods, it's still possible apply additional constraints kernel::schedule().
depending on needs, there 2 ways it.
if want set custom cron expression event, can use cron() method:
protected function schedule(schedule $schedule) { $schedule->call(function () { //scheduled code })->cron('0 1 2 * * *')->daily(); }
if need apply cron constraints using existing methods, need modify later way weekdays() using spliceintoposition, can access calling getexpression(), modify it, , set using cron().
protected function schedule(schedule $schedule) { $event = $schedule->call(function () { //scheduled code }); $scheduledat = $event->getexpression(); //get cron expression ...; //modify $scheduledat expression $event->cron($scheduledat); // set new schedule }
if want reuse logic multiple events, can add helper functions in kernel.php, e.g.:
protected function specialschedule(\illuminate\console\scheduling\event $event) { $scheduledat = $event->getexpression(); ...; // modify $scheduledat expression $event->cron($scheduledat); return $event; }
then can reuse logic when defining schedule:
protected function schedule(schedule $schedule) { $this->specialschedule($schedule->call(function () { //scheduled code })); }
update:
there 1 more way - bit more complex, requires provide own schedule , event classes, more flexible.
first, implement own event class , add there new methods:
class customevent extends \illuminate\console\scheduling\callbackevent { public function weekends() { return $this->days(6,7); } }
then own schedule class, creates customevent objects:
class customschedule extends \illuminate\console\scheduling\schedule { public function call($callback, array $parameters = []) { $this->events[] = $event = new customevent($callback, $parameters); return $event; } public function exec($command, array $parameters = []) { if (count($parameters)) { $command .= ' '.$this->compileparameters($parameters); } $this->events[] = $event = new event($command); return $event; } }
lastly, in kernel.php need make sure new schedule class used scheduling:
protected function defineconsoleschedule() { $this->app->instance( 'illuminate\console\scheduling\schedule', $schedule = new schedule ); $this->schedule($schedule); }
Comments
Post a Comment