實驗環(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定時任務是由系統(tǒng)自帶的crontab功能實現(xiàn)的伏穆,可以指定時間間隔或者特定命令的功能。與特定的編程語言和編程環(huán)境無關纷纫。
此次實驗的是PHP laravel框架的定時任務實現(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
便會每分鐘執(zhí)行一次任務了
===================================================================================================
此次cron.txt中包含的PHP命令是定期執(zhí)行l(wèi)aravel框架中定義的定時任務辱魁,所以我們要在laravel補充完整相關的任務定義烟瞧。
laravel中的定時任務可以有很多種類型,這次我們使用命令的形式來定義定時任務染簇。
在 App\Console\Commands\LogInfo 定義一個記錄日志的方法参滴。
<?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的計劃任務調(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 日志中每個1分鐘會出現(xiàn)以下記錄锻弓,即表示定時任務成功部署
[2018-09-15 10:30:01] local.INFO: Crontab routing job.