Is there a way to get the scheduled task as an array from a controller? [duplicate]
Asked Answered
S

1

1

I would like to get the scheduled tasks list from a controller. Some packages, articles and even StackOverflow explain how to display it from a command, but I did not found how to do it without a command. My goal is to get an array of scheduled task with their date and description.

Is there a way to get the scheduled task as an array (or an object list, or anything that can be easily handled) from a controller?

Subantarctic answered 10/1, 2018 at 14:50 Comment(2)
#35560269Sclerometer
I think the answer here has use, as it does some parsing of the returned events, but the question you linked to already had a 2016 answer showing how to do it in a controller. It was not a well-written answer (I've cleaned it up) but it presented a very similar solution.Academic
S
8

Here is a way to get all scheduled tasks:

use Carbon\Carbon;
use Cron\CronExpression;
use Illuminate\Support\Str;

app()->make(\Illuminate\Contracts\Console\Kernel::class);
$schedule = app()->make(\Illuminate\Console\Scheduling\Schedule::class);

$events = collect($schedule->events())->map(function($event) {
    $cron = CronExpression::factory($event->expression);
    $date = Carbon::now();
    if ($event->timezone) {
        $date->setTimezone($event->timezone);
    }

    return (object) [
        'expression'  => $event->expression,
        'command'     => Str::after($event->command, '\'artisan\' '),
        'next_run_at' => $cron->getNextRunDate()->format('Y-m-d H:i:s'),
    ];
});

You have a collection of objects (in $events) with three properties:

  • expression - example: 12 1 * * *
  • command - example: mypackage:mycommand
  • next_run_at - example: 2018-01-10 16:50:49
Subantarctic answered 10/1, 2018 at 16:26 Comment(3)
I tried this solution, but showing error: {message: "Class 'App\Http\Controllers\CronExpression' not found",…}...Myelitis
@AnoopSankar assuming you enter this in tinker, you can either type use \Cron\CronExpression; or use the full namespace instead of the class. You will need use \Carbon\Carbon; as well and for people working with Larvael versions lower than 5.4, the str_after helper is unavailable and you will have to define it yourself: function str_after($subject,$search) { return $search === '' ? $subject : array_reverse(explode($search, $subject, 2))[0]; }Roccoroch
That is useful. Just one question, if I add a job with some parameters to the schedule, I haven't found a way to retrieve the parameters value with this approach. Example: $schedule->job(new CommandJob($value->command, $value->is_curl))->cron($value->schedule); I would like to get the 2 parameters i passed to the job otherwise in the list I have 5 CommandJob but I don't know what they're makingWhatever

© 2022 - 2024 — McMap. All rights reserved.