1、在modules\article\src\Commands下创建了ArticlesCommand.php文件
ArticlesCommand.php内容如下:
<?php
namespace Article\Commands;
use App\Models\ArticleContents;
use Illuminate\Console\Command;
use App\Models\Article;
use Carbon\Carbon;
class ArticlesCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'articles:cron';
/**
* The console command description.
*
* @var string
*/
protected $description = '删除前一天的文章';
/**
* Execute the console command.
*/
public function handle()
{
$yesterday = Carbon::yesterday();
\DB::transaction(function () use ($yesterday) {
ArticleContents::whereDate('created_at', $yesterday)->delete();
$deletedCount = Article::whereDate('created_at', $yesterday)->delete();
$this->info("已删除 {$deletedCount} 篇前一天的文章");
\Log::info("定时任务删除文章", ['count' => $deletedCount]);
});
}
}
2、在当前目录src下的ServiceProvider.php
ServiceProvider文件内容如下:
<?php
declare(strict_types = 1);
namespace Article;
use Article\Commands\ArticlesCommand;
use Article\Commands\DemoCronCommand;
use Article\Http\RouteServiceProvider;
use Weiran\Framework\Exceptions\ModuleNotFoundException;
use Weiran\Framework\Support\WeiranServiceProvider;
use Illuminate\Console\Scheduling\Schedule;
class ServiceProvider extends WeiranServiceProvider
{
/**
* 定义模块名称
* 模块使用 module.{module}
*/
protected $name = 'Article.article';
/**
* Bootstrap the module services.
* @return void
* @throws ModuleNotFoundException
*/
public function boot(): void
{
parent::boot('article');
if ($this->app->runningInConsole()) {
$this->app->booted(function () {
$schedule = $this->app->make(Schedule::class);
$schedule->command('articles:cron')->everyMinute();
});
}
}
/**
* Register the module services.
* @return void
*/
public function register(): void
{
$this->app->register(RouteServiceProvider::class);
// 注册命令
$this->commands([
DemoCronCommand::class,
ArticlesCommand::class,
]);
}
}
3、在 config/app.php 文件中添加如下内容:
'providers' => [
\Article\ServiceProvider::class,
]
4、手动测试下是否执行成功、成功会提示执行成功。
php artisan articles:cron
5、启动开发环境实时测试请求:
php artisan schedule:work
成功会显示:
[2023-05-20 10:00:00] Running scheduled command: php artisan article:demo-task
[2023-05-20 10:00:00] 任务执行成功: 2023-05-20 10:00:00