如何在laravel中创建一个函数,该函数将在服务器运行时始终运行



因此,我想创建一个函数来不断更新我的产品库存并且我需要该函数在服务器或应用程序运行时持续运行.....

提前感谢!!

我的期望:

while (true)
{
$product->quantity += $updated
// This would be running continuously     
}

好的,经过一些帮助,我得到了解决方案,使用laravel命令与任务调度最少可用运行每一分钟。

,创建一个新命令:

php artisan make:command ProductQuantityUpdate // Command Name

,在AppConsoleCommandsProductQuantityUpdate.php中找到ProductQuantityUpdate.php并在handle()中键入所需的函数:

注意:您也可以编辑命令名称&通过:

描述
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'productquantity:update';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Update Product Quantity!';

完整代码[AppConsoleCommandsProductQuantityUpdate.php]:

<?php
namespace AppConsoleCommands;
use IlluminateConsoleCommand;
class ProductQuantityUpdate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'productquantity:update';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Update Product Quantity!';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$pro = AppModelsProduct::get();
foreach($pro as $product)
{
$qty = 0;
$selecteds = AppModelsAttributeValue::where('product_id', $product->id)->get();
if($selecteds->count() > 0)
{
foreach($selecteds as $select)
{
$qty += $select->quantity;
}
$product->quantity = $qty;
$product->save();
}
}
$this->info('Product Quantity Updated!');
return Command::SUCCESS;
}
}

第三,进入AppConsoleKernel.php,添加命令和调度功能:

protected $commands = [
CommandsProductQuantityUpdate::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('productquantity:update')->everyMinute(); 
// Check the documentation for available timings!
}

要检查命令,请在控制台中输入以下命令:

php artisan list

要检查您的日程安排,请在控制台中键入:

php artisan schedule:list

对我有帮助的文档:Couldways文档

最新更新