laravel add scheduler dynamically

2020-02-11 05:39发布

问题:

I have a system where the user can create background tasks via the UI.
The task interval are every few hours (user choice in the UI).

when the user creates a task via the ui i want to add it to the scheduler dynamically.

As the example states, this is static and not dynamic.

protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        DB::table('recent_users')->delete();
    })->daily();
}

Is it possible? if not, what are the alternatives?

Thanks

回答1:

I don't see why it wouldn't be possible. The Kernel::schedule method will be run every time php artisan schedule:run is run. If you set it up like the documentation, should be every minute via a cron.

* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

With that in mind, I don't see why you can't do something like this:

protected function schedule(Schedule $schedule)
{
    // Get all tasks from the database
    $tasks = Task::all();

    // Go through each task to dynamically set them up.
    foreach ($tasks as $task) {
        // Use the scheduler to add the task at its desired frequency
        $schedule->call(function() use($task) {
            // Run your task here
            $task->execute();
        })->cron($task->frequency);
    }
}

Depending on what you store, you can use whatever you like here instead of the CRON method. You might have a string stored in your database that represents one of Laravel's predefined frequencies and in which case you could do something like this:

$frequency = $task->frequency; // everyHour, everyMinute, twiceDaily etc.
$schedule->call(function() {
    $task->execute();
})->$frequency();

The main thing to note here, is that the schedule isn't actually scheduling in tasks in the database or in a cron that it manages. Every time the scheduler runs (Every minute) it runs and it determines what to run based on the frequencies you give each task.

Example:

  • You have a task set up using ->hourly(), that is, to run on the hour, every hour.
  • At 00:00, the schedule runs, the ->hourly() filter passes, because the time is on the hour, so your task runs.
  • At 00:01, the schedule runs and but this time the ->hourly() filter fails, so your task does not run.