本文實例講述了Laravel框架定時任務2種實現方式。分享給大家供大家參考,具體如下:
第一種
1、生成一個commands文件
> php artisan make:command test
2、打開文件進行修改
laravel\App\Console\Commands\test.php
?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class test extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'test:insert'; // php artisan list 中將會生成 "php artisan test:insert " 指令
/**
* The console command description.
*
* @var string
*/
protected $description = 'insert Test table some test data'; // 對上面指令的描述
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// 編寫你要的定時任務執行的代碼!
# eg
Log::info('test');
}
}
> php artisan list
查看

3、然后修改: laravel\app\Console\Kernel.php 文件
?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
// 參考手冊 新加
\App\Console\Commands\test::class,
];
// 定義應用的命令調度
protected function schedule(Schedule $schedule)
{
// 新加 每分鐘執行一次
$schedule->command('test:insert')->everyMinute();
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
4、啟用計劃任務:在服務器中加入到計劃任務 crontab -e
注意這里的 path 是你的laravel項目根目錄的 絕對路徑!, 然后加上后面的 artisan 到結尾的字符串
* * * * * php /path/artisan schedule:run >> /dev/null 2>1
* * * * * php /code/src/laravel/artisan schedule:run >> /dev/null 2>1
5、打開日志文件查看
laravel\storage\logs\laravel.log
第二種
使用 shell腳本執行
因為 php artisan list
可以查看到 執行指令 test:insert
所以可以考慮用 .sh 腳本執行,還是類似上面 crontab -e
編寫
1、先編寫 .sh 腳本 laravel/test.sh 放在項目某個位置,文件內寫入
上面指令在命令行手動每執行一次就可以觸發一次編寫的程序,相當于給 laravel.log 寫入一次 test
2、使用 crontab -e
編寫 執行 第一步寫的 test.sh 腳本
* * * * * laravel/test.sh
以上兩種均可看到 laravel.log 日志

更多關于Laravel相關內容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優秀開發框架總結》、《php面向對象程序設計入門教程》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家基于Laravel框架的PHP程序設計有所幫助。
您可能感興趣的文章:- Laravel實現定時任務的示例代碼
- Laravel框架實現定時發布任務的方法
- 源碼分析 Laravel 重復執行同一個隊列任務的原因
- Laravel中任務調度console使用方法小結
- Laravel框架數據庫CURD操作、連貫操作總結
- Laravel框架表單驗證詳解
- Laravel框架中擴展函數、擴展自定義類的方法
- 跟我學Laravel之快速入門
- Laravel框架路由配置總結、設置技巧大全
- Laravel中使用FormRequest進行表單驗證方法及問題匯總