今天作商城项目的时候,须要将用户的待付款订单一个小时后自动取消。那么这个操做,不多是人为的,只能借助
linux
的cron
来进行作定时任务了。php
总体思路:
首先,在 Order
模型里写一个 public
方法,将查询到的半个小时以外还没付款的订单,将其状态所有改成 已取消的状态。
其次,自定义命令,执行该方法。
最后呢,就是将其命令注册到调度任务里自动执行便可。linux
// 在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());
}
复制代码
首先跑如下生成命令类缓存
php artisan make:command CancelUnpaidOrder --command=asshop:cancel-unpaid-order
复制代码
执行完,以后就能够打开生成的类文件app\CancelUnpaidOrder.phpbash
<?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("执行成功!");
}
}
复制代码
而后执行下面命令就能执行编写的方法。app
php artisan larabbs:cancel-unpaid-order
复制代码
更新app/Console/Kernel.phpssh
<?php
.
.
.
class Kernel extends ConsoleKernel {
.
.
.
protected function schedule(Schedule $schedule) {
// 一小时执行一次『活跃用户』数据生成的命令
$schedule->command('asshop:cancel-unpaid-order')->everyMinute();
}
.
.
.
}
复制代码
linux
的cron
进行定时执行//编辑crontab
export EDITOR=vi && crontab -e
复制代码
添加你的命令到crontab里 ,写本身的php路径 和项目的路径~ui
* * * * * /www/server/php/72/bin/php /www/wwwroot/asshop/artisan schedule:run >> /dev/null 2>&1
复制代码
千万要注意必定要用绝对路径哟~表示踩坑过来的。this
大功告成~spa