Laravel 5 有自己的处理排队作业的方式,但您仍然可以使用 Laravel 4 中可用的选项。我个人一直很好奇它是如何工作的,只是将一个空白项目放在一起并运行在文档的帮助下有几个排队的工作,所以这可能不是一个完整的答案,但我希望这对你有所帮助。
首先,您需要将配置设置为使用database 队列驱动程序,这可以在config/queue.php 中完成,或者对我来说,只需转到.env 文件并执行以下操作:QUEUE_DRIVER=database .
然后你想设置数据库表来保存排队的作业,你可以通过运行 artisan 命令来做到这一点:php artisan queue:table 这将创建迁移,所以你需要通过运行 php artisan migrate 和那么你的数据库中就会有你的工作表。
之后,您需要设置一个以命令形式出现的排队作业。例如,我将设置一个将一些文本写入日志文件的作业。您可以使用工匠命令创建作业或命令,这是我创建命令时所做的:php artisan make:command WriteToLog --queued。这是我的命令类在添加一些代码以使其写入日志文件后的样子...
app/Commands/WriteToLog.php
use App\Commands\Command;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldBeQueued;
class WriteToLog extends Command implements SelfHandling, ShouldBeQueued {
use InteractsWithQueue, SerializesModels;
protected $secs;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct($secs)
{
$this->secs = $secs;
}
/**
* Execute the command.
*
* @return void
*/
public function handle()
{
\Log::info('Writing to the log in ' . $this->secs);
}
}
创建命令后,为了测试它,我在路由文件中写了一条路由...
app/Http/routes.php
Route::get('/', function(){
// some time to delay the job
$fiveSecs = \Carbon\Carbon::now()->addSeconds(5);
$tenSecs = \Carbon\Carbon::now()->addSeconds(10);
// adds job to queue
Queue::later($fiveSecs, new App\Commands\WriteToLog('5 secs'));
Queue::later($tenSecs, new App\Commands\WriteToLog('10 secs'));
return 'All done';
});
在我们点击我们想要侦听任何作业以处理它们的路线之前,只需运行 php artisan queue:listen 然后您可以转到浏览器到该路线,在我的浏览器中点击该路线后控制台显示
$ php artisan queue:listen
Processed: Illuminate\Queue\CallQueuedHandler@call
Processed: Illuminate\Queue\CallQueuedHandler@call
如果我检查我的日志文件,我会看到以下内容:
[2015-05-19 19:25:08] local.INFO: Writing to the log in 5 secs
[2015-05-19 19:25:10] local.INFO: Writing to the log in 10 secs
并不完全相隔 5 秒和 10 秒,但希望你能明白!
对我来说,这只是冰山一角,排队作业在 laravel 中非常强大,我强烈建议您在此处查看文档:http://laravel.com/docs/5.0/queues 和此处:http://laravel.com/docs/5.0/bus
您还可以从排队的作业中触发事件或将事件处理程序排队,请参阅此处了解更多详细信息:http://laravel.com/docs/5.0/events#queued-event-handlers