實(shí)驗(yàn)環(huán)境
操作系統(tǒng):Ubuntu 16.04.1 LTS
參考文章
https://www.cnblogs.com/lamp01/p/6864258.html
https://blog.csdn.net/a_new_steven/article/details/73733087
linux定時(shí)任務(wù)是由系統(tǒng)自帶的crontab功能實(shí)現(xiàn)的,可以指定時(shí)間間隔或者特定命令的功能。與特定的編程語言和編程環(huán)境無關(guān)。
此次實(shí)驗(yàn)的是PHP laravel框架的定時(shí)任務(wù)實(shí)現(xiàn)
在laravel根目錄下生成 cron.txt 文件,內(nèi)容為
* * * * * php /home/bella/Downloads/lnmp/echo1.0/echo/artisan schedule:run >> /dev/null 2>&1
將文件路徑傳給crontab,crontab- l執(zhí)行
crontab cron.txt
crontab -l
便會(huì)每分鐘執(zhí)行一次任務(wù)了
===================================================================================================
此次cron.txt中包含的PHP命令是定期執(zhí)行l(wèi)aravel框架中定義的定時(shí)任務(wù),所以我們要在laravel補(bǔ)充完整相關(guān)的任務(wù)定義。
laravel中的定時(shí)任務(wù)可以有很多種類型,這次我們使用命令的形式來定義定時(shí)任務(wù)。
在 App\Console\Commands\LogInfo 定義一個(gè)記錄日志的方法。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class LogInfo extends Command
{
? ? /**
? ? * The name and signature of the console command.
? ? *
? ? * @var string
? ? */
? ? protected $signature = 'lesson:log';
? ? /**
? ? * The console command description.
? ? *
? ? * @var string
? ? */
? ? protected $description = 'Log Info';
? ? /**
? ? * Create a new command instance.
? ? *
? ? * @return void
? ? */
? ? public function __construct()
? ? {
? ? ? ? parent::__construct();
? ? }
? ? /**
? ? * Execute the console command.
? ? *
? ? * @return mixed
? ? */
? ? public function handle()
? ? {
? ? ? ? Log::info('Crontab routing job. ');
? ? }
}
Laravel的計(jì)劃任務(wù)調(diào)用是在 App\Console\Kernel 中的 schedule 方法中
在command方法中填入我們上面定義的'lesson:log'命令即可。
protected function schedule(Schedule $schedule)
? ? {
? ? ? ? // $schedule->command('inspire')
? ? ? ? //? ? ? ? ? ->hourly();
? ? ? ? $schedule->command('lesson:log')->everyMinute();
? ? }
如果 laravel目錄下的 storage\logs\laravel.log 日志中每個(gè)1分鐘會(huì)出現(xiàn)以下記錄,即表示定時(shí)任務(wù)成功部署
[2018-09-15 10:30:01] local.INFO: Crontab routing job.