The Laravel framework allows you to set up scheduled tasks so that you don't have to worry about setting them up at the system level. You can get rid of that complex cron syntax while setting up scheduled tasks since Laravel allows you to define them in a user-friendly way.
Here’s a text representation that should clarify how cron works
# Use the hash sign to prefix a comment # +---------------- minute (0 - 59) # | +------------- hour (0 - 23) # | | +---------- day of month (1 - 31) # | | | +------- month (1 - 12) # | | | | +---- day of week (0 - 7) (Sunday=0 or 7) # | | | | | # * * * * * command to be executed #-----------------------------------------------------------
1) let's create a command:
app/Console/Commands
namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Carbon; class CheckLogFileSize extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'logfilesize:check'; /** * The console command description. * * @var string */ protected $description = 'Check the log file size daily and send email if filesize grows fast'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { //2019-06-05 $today = Carbon::today()->format('Y-m-d'); $file = storage_path('logs'). '/lumen-' . $today . '.log'; if($logsize >= 100){ $content = $file . ' size is growing very fast, please deal with it as soon as possible.'; $toMail = '<a href="mailto:546131320@qq.com">546131320@qq.com</a>'; $message->subject('Warning!!!, Log file size now is ' . $logsize . 'MB'); $message->to($toMail); }); } } }
2) Edit Kernel.php file
namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Laravel\Lumen\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ //mail test Commands\SendMailCommand::class, Commands\CheckLogFileSize::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('logfilesize:check') ->everyThirtyMinutes(); } }
For testing:
php artisan logfilesize:check
3) Add scheduler to cron by running crontab -e
crontab -e
Add the following code to cron editor:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1