问题描述
我有一个系统,用户可以在其中通过UI创建后台任务.
任务间隔为每隔几个小时(用户界面中的用户选择).
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).
当用户通过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?
谢谢
推荐答案
我不知道为什么不可能.每次运行php artisan schedule:run
时,都会运行Kernel::schedule
方法.如果您像文档一样进行设置,则应每分钟通过cron.
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);
}
}
根据您存储的内容,您可以在这里使用任何您喜欢的东西来代替CRON方法.您可能在数据库中存储了一个字符串,该字符串表示Laravel的预定义频率之一,在这种情况下,您可以执行以下操作:
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();
这里要注意的主要事情是,调度实际上并不是在数据库或其管理的cron中的任务中调度.调度程序每次运行时(每分钟)都会运行一次,并根据您为每个任务分配的频率来确定要运行的内容.
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.
示例:
- 您有一个使用
->hourly()
设置的任务,即每小时运行一次. - 在
00:00
,计划运行,->hourly()
过滤器通过,因为时间是小时,所以您的任务在运行. - 在
00:01
,计划已运行,但是这次->hourly()
筛选器失败,因此您的任务无法运行.
- 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.
这篇关于laravel动态添加调度程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!