在 Laravel 中,你可以通过创建 Artisan 命令并结合 Linux 的 cron
定时任务来实现类似 ThinkPHP5 的 think command
的持久运行任务。以下是具体步骤:
1. 创建 Artisan 命令
首先,你需要创建一个 Artisan 命令。你可以使用 make:command
Artisan 命令来生成一个新的命令类。
php artisan make:command YourCustomCommand
这会在 app/Console/Commands
目录下生成一个新的命令类文件,例如 YourCustomCommand.php
。
2. 编写命令逻辑
打开生成的命令类文件,你可以在 handle
方法中编写你的任务逻辑。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class YourCustomCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'your:custom-command';
/**
* The console command description.
*
* @var string
*/
protected $description = 'This is a custom command for your task';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
// 在这里编写你的任务逻辑
$this->info('Your custom command is running...');
// 例如:处理某些数据
// YourLogic::process();
return 0;
}
}
3. 注册命令
确保你的命令已经在 app/Console/Kernel.php
文件中注册。通常,新生成的命令会自动注册,但你可以手动检查一下。
protected $commands = [
Commands\YourCustomCommand::class,
];
4. 设置 Linux 定时任务 (Cron)
接下来,你需要设置 Linux 的 cron
定时任务来定期执行这个 Artisan 命令。
4.1 编辑 Crontab
使用 crontab -e
命令编辑当前用户的 crontab 文件。
crontab -e
4.2 添加定时任务
在 crontab 文件中添加一行来定期执行你的 Artisan 命令。例如,每分钟执行一次:
* * * * * php /path/to/your/laravel-project/artisan your:custom-command >> /dev/null 2>&1
* * * * *
表示每分钟执行一次。/path/to/your/laravel-project/artisan
是你的 Laravel 项目的artisan
文件的绝对路径。your:custom-command
是你定义的 Artisan 命令的名称。>> /dev/null 2>&1
用于将输出重定向到/dev/null
,避免产生不必要的日志文件。
4.3 保存并退出
保存并退出编辑器,cron 会自动加载新的配置。
5. 测试定时任务
你可以手动运行一次命令来测试它是否正常工作:
php artisan your:custom-command
如果一切正常,你应该会看到命令输出的信息。
6. 持久运行任务
如果你希望任务在后台持久运行(例如,类似于守护进程),你可以使用 nohup
或 supervisor
来管理进程。
6.1 使用 nohup
nohup php /path/to/your/laravel-project/artisan your:custom-command > /dev/null 2>&1 &
6.2 使用 supervisor
supervisor
是一个进程管理工具,可以确保你的任务在崩溃后自动重启。你可以通过以下步骤配置 supervisor
:
-
安装
supervisor
:sudo apt-get install supervisor
-
创建一个新的配置文件,例如
/etc/supervisor/conf.d/laravel-worker.conf
:[program:laravel-worker] process_name=%(program_name)s_%(process_num)02d command=php /path/to/your/laravel-project/artisan your:custom-command autostart=true autorestart=true user=your-user numprocs=1 redirect_stderr=true stdout_logfile=/path/to/your/laravel-project/storage/logs/worker.log
-
更新
supervisor
配置并启动任务:sudo supervisorctl reread sudo supervisorctl update sudo supervisorctl start laravel-worker:*
总结
通过以上步骤,你可以在 Laravel 中创建一个自定义的 Artisan 命令,并使用 Linux 的 cron
或 supervisor
来定时或持久运行该任务。这种方式类似于 ThinkPHP5 中的 think command
。