Laravel定时任务

在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命令,查看正在运行的定时任务。

(完)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Crocutax

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值