您可以让作业在结尾处广播一个将附加侦听器的事件。这个听众然后会派遣一份工作再次完成这项工作。
php artisan make:job LoopUserPosts
$posts = $user->posts;
$posts->each(function($post){
//your work on your post
if($post->id === $posts->count()){
// broadcast your event here
event(App\Events\UserPostsLoopEnded, [$post->user]);
}
});
事件可以是这样的:
php artisan make:event UserPostsLoopEnded
class UserPostsLoopEnded extends Event
{
use SerializesModels;
public $user;
public function __construct(App\User $user)
{
$this->user = $user;
}
}
然后我们需要建立一个监听器:
php artisan make:listener HandleUserPostsLoopEnded --event="UserPostsLoopEnded"
use App\Events\UserPostsLoopEnded;
class HandleUserPostsLoopEnded
{
public function __construct()
public function handle(UserPostsLoopEnded $event)
{
//now we can just dispatch the job again
dispatch(App\Jobs\LoopUserPosts, [$event->user]
}
}
那么你当然需要attach the listener
。继续并打开App\Providers\EventServiceProvider
,然后确保我们将我们的活动和我们的听众添加到$listen
阵列。
protected $listen = [
//.....
'App\Events\UserPostsLoopEnded' => [
'App\Listeners\HandleUserPostsLoopEnded',
],
];
现在我们有一个完整的端到端。一旦工作完成,它将播出一个事件。监听者一旦被触发就会收到事件。听众将再次派遣工作,传递给用户。
通常,队列作业旨在处理后台中长时间运行的进程。一些常见的队列作业的例子是文件上传或视频编码等。我很好奇:为什么你认为你需要排队作业来处理检索邮件记录?更进一步,你为什么要让队列永久运行?你能再描述一下你的用例吗? – maiorano84
我在每个用户的帖子上执行操作,我需要不断地执行此操作。知道用户列表非常短,帖子数量很少。 – user6592471