Laravel——自定义命令command
程序员文章站
2022-06-07 14:25:33
...
今天做商城项目的时候,需要将用户的待付款订单一个小时后自动取消。那么这个操作,不可能是人为的,只能借助
linux
的cron
来进行做定时任务了。
整体思路:
首先,在 Order
模型里写一个 public
方法,将查询到的半个小时之外还没付款的订单,将其状态全部改为 已取消的状态。
其次,自定义命令,执行该方法。
最后呢,就是将其命令注册到调度任务里自动执行即可。
1.编写public cancelUnpaidOrder的方法
// 在Order模型里
public function cancelUnpaidOrder() {
self::where('status', 1)
->where('created_at', '<=', date('Y-m-d H:i:s',time() - 30 * 60))
->update(['status' => 0]);//我这里的状态为0 就是代表取消订单
//清除缓存(一般做了缓存的这里得清除一下)
Cache::forget('status_counts_'.Auth::id());
Cache::forget('count_all'.Auth::id());
}
2.自定义命令
php artisan make:command CancelUnpaidOrder --command=asshop:cancel-unpaid-order
执行完,之后就可以打开生成的类文件app\CancelUnpaidOrder.php
<?php
namespace App\Console\Commands;
use App\Models\Shop\Order;
use Illuminate\Console\Command;
class CancelUnpaidOrder extends Command
{ // 供我们调用命令
protected $signature = 'asshop:cancel-unpaid-order';
// 命令的描述
protected $description = '定时自动取消待付款订单';
// 最终执行的方法
public function handle(Order $order)
{
// 在命令行打印一行信息
$this->info("开始查找...");
$order->cancelUnpaidOrder();
$this->info("执行成功!");
}
}
3.然后执行下面命令就能执行编写的方法。
php artisan larabbs:cancel-unpaid-order
4.注册到调度任务(更新app/Console/Kernel.php)
<?php
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected function schedule(Schedule $schedule)
{
// 一小时执行一次『活跃用户』数据生成的命令
$schedule->command('asshop:cancel-unpaid-order')->everyMinute();
}
}
5.利用linux
的cron
进行定时执行
//编辑crontab
export EDITOR=vi && crontab -e
添加你的命令到crontab里 ,写自己的php路径 和项目的路径~
* * * * * /www/server/php/72/bin/php /www/wwwroot/asshop/artisan schedule:run >> /dev/null 2>&1
千万要注意一定要用绝对路径哟~表示踩坑过来的。
这样就好了,是不是很方便~
上一篇: Maven 使用maven-assembly-plugin打包可执行jar,No auto configuration classes found in META-INF/spring.factori
下一篇: C#命令语句使用
推荐阅读
-
C#命令模式(Command Pattern)实例教程
-
Laravel如何自定义command命令浅析
-
C#命令模式(Command Pattern)实例教程
-
Laravel如何自定义command命令浅析
-
Laravel执行migrate命令提示:No such file or directory的解决方法
-
天正T20软件怎么修改快捷键?天正T20自定义快捷键命令的方法介绍
-
Laravel学习笔记之Artisan命令生成自定义模板的方法
-
Laravel框架Eloquent ORM新增数据、自定义时间戳及批量赋值用法详解
-
Animate怎么自定义设置快捷键命令?
-
Laravel+Dingo/Api 自定义响应的实现