在JavaEE中实现定时任务非常简单,再配合强大的Spring,相当轻松。在PHP项目中,Laravel框架的Command
配合Linux 的crontab
服务,虽然略微麻烦一点,但是更加灵活。
具体可查看 Laravel学院的文档 ,文档中有更加详尽的使用流程和方法介绍。但是自己当时只看文档,并没有写出立竿见影生效的demo,还是浪费了一些时间去搜索,不过回过头来看,基本上也就是文档里说的那些东西,在此只做简单记录。
1.创建任务
在项目目录下执行artisan命令php artisan make:command CheckOrderIn
,创建任务
$ php artisan make:command CheckOrderIn
Console command created successfully.
此命令会在app/Console/Commands
目录下创建CheckOrderIn
文件,文件结构清晰明了,不多做阐述
class CheckOrderIn extends Command
{
/**
* 任务签名,该签名用于加入Laravel调度计划
*/
protected $signature = 'command:CheckOrderIn';
/**
* 任务描述
*
*/
protected $description = '检测入库单是否已被经销商确认';
/**
* Create a new command instance.
*/
public function __construct()
{
parent::__construct();
}
/**
* 要执行的任务
*/
public function handle()
{
//do something ...
}
}
2.加入Laravel调度计划
在app/Console/Kernel.php
文件中,加入上一步定义的任务
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* 定义Artisan 命令
* @var array
*/
protected $commands = [
CheckOrderIn::class
];
/**
* Define the application's command schedule.
*
* 定义调度任务
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('command:CheckOrderIn')
->everyMinute();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
在schedule ( )
方法中,可以定义任务执行的频率,具体可参考文章开头提到的文档,包括钩子的使用等等。
现在,就可以通过如下artisan命令 php artisan schedule:run
进行任务的测试了
$ php artisan schedule:run
Running scheduled command: '/usr/local/Cellar/php/7.2.7/bin/php' 'artisan' command:CheckOrderIn > '/dev/null' 2>&1
执行完之后,会发现在CheckOrderIn
中定义的任务,已经执行了,不过,只执行一次而已,如果要真正的实现定时任务,还需要Linux的crontab
的配合
3.crontab执行任务
通过crontab e
编辑脚本,输入以下内容,新增一条Cron
命令
* * * * * /usr/bin/php /mnt/php/oms/artisan schedule:run >> /dev/null 2>&1
/usr/bin/php
连接到php的可执行文件目录,/mnt/php/oms/artisan
则是自己项目的根目录,以上两个随自己的配置而调整。
配置完以后,步骤2中的任务就可以正常的按频率执行了。如果发现步骤2可以正常运行,但是这一步配置完以后,却无法按配置的频率执行任务,那么一定是php文件目录及项目目录配置的有问题。
最后,可以通过crontab -l
命令,查看正在运行的定时任务。
(完)