laravel 5.6

创建

php artisan make:job ProcessPodcast

编辑 App\Jobs\ProcessPodcast

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
namespace App\Jobs;

use App\AudioProcessor;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class ProcessPodcast implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

protected $podcast;

// 主要用于传值
public function __construct($data)
{
$this->data = $data;
}

// 主要运行逻辑
public function handle()
{
// ...
}
}

分发任务

No.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace App\Http\Controllers;

use App\Jobs\ProcessPodcast;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PodcastController extends Controller
{
public function store(Request $request)
{
// ...
// 分发任务
ProcessPodcast::dispatch($datas);
}
}

No.2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace App\Http\Controllers;

use App\Jobs\ProcessPodcast;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PodcastController extends Controller
{
public function store(Request $request)
{
// ...
// 分发任务
dispatch(new ProcessPodcast($datas));

// 也可以这样写
$this->dispatch(new ProcessPodcast($datas));
}
}

运行队列

# 测试
php artisan queue:listen

# 线上
php artisan queue:work

推荐使用 horizon
horizon 使用方法