【问题标题】:Laravel run artisan command every 5 secondsLaravel 每 5 秒运行一次 artisan 命令
【发布时间】:2015-05-15 18:45:52
【问题描述】:

我正在使用一个系统,只要该系统中的资源发生更改,它就会向我发送 webhook。 Webhook 包含已更新资源的 ID。例如,如果有人在此系统中编辑产品 ID 1234,我的服务器将收到一条警报,指出产品 1234 已更改。然后我向他们的 API 发出请求,以获取产品 1234 的最新数据并将其保存到我的系统中。

我正在构建这个过程以异步工作。这意味着,每次收到 webhook 时,我都会将详细信息保存到记录资源 ID 的数据库表中。然后我有一个WebhookQueue 类,其中包含一个run() 方法,它处理所有排队的请求并更新相应的产品。这是来自WebhookQueue 类的代码:

public static function run()
{
        //get request data
        $requests = WebhookRequest::select(
                        'webhook_type',
                        'object_ext_id',
                        'object_ext_type_id',
                        \DB::raw('max(created_at) as created_at')
                )
                ->groupBy(['webhook_type', 'object_ext_id', 'object_ext_type_id'])
                ->get();

        foreach ($requests as $request) {
                // Get the model for each request.
                // Make sure the model is not currently syncing.
                // Sync the model.
                // Delete all webhook request of the same type that were created before created_at on the request
                if ($request->webhook_type == 'product') {
                        $model = Product::where([
                                        'ext_id'=> $request->object_ext_id,
                                        'ext_type_id'=> $request->object_ext_type_id
                                ])->firstOrFail();

                        if (!$model->is_syncing) {
                                $model->syncWithExternal();

                                WebhookRequest::where([
                                        'webhook_type'=>$request->webhook_type,
                                        'object_ext_id'=>$request->object_ext_id,
                                        'object_ext_type_id'=>$request->object_ext_type_id,
                                ])
                                ->where('created_at', '<=', $request->created_at)
                                ->delete();
                        }
                }
        }
}

我还创建了一个命令,它只执行一行代码来处理队列。这个命令是php artisan run-webhook-queue

我的计划是每 5 秒通过一个 cron 作业运行此命令,但我刚刚了解到不能比按分钟更精细地安排 cron 作业。

我怎样才能让这个命令每 5 秒运行一次,或者我应该有其他方法来处理这种情况吗?我对 Laravel 队列一无所知,但似乎我应该使用它。

【问题讨论】:

  • 如果您每 5 秒运行一次,在收到警报时处理请求不是更有意义吗?
  • 有时外部系统会为同一个更改发送多个 webhook。在这些情况下,我收到一个又一个请求,但实际上应该只同步一次。异步执行此操作更有意义,因此可以将这两个 webhook 组合在一起。此外,5 秒的间隔可能会改变。

标签: php laravel cron


【解决方案1】:

Laravel Worker Queues 可以很好地处理这个问题,并且允许你每 5 秒运行一次命令。如果您使用 Forge,则安装几乎没有任何工作。

这是使用 Forge 的指南:https://mattstauffer.co/blog/laravel-forge-adding-a-queue-worker-with-beanstalkd

如果您不使用 Forge,这里是一个指南:http://fideloper.com/ubuntu-beanstalkd-and-laravel4

【讨论】:

  • 谢谢,我在 Google 搜索中深入了几页后才发现了同样的指南。看起来那些应该可以帮助我得到我需要的东西。
猜你喜欢
  • 2020-09-18
  • 2014-08-21
  • 2016-09-11
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 2017-10-14
  • 2011-03-20
  • 2016-07-30
相关资源
最近更新 更多