This article brings you an introduction to laravel task scheduling (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Introduction: I have written about using Linux to perform scheduled tasks before. In fact, laravel can also perform scheduled tasks. The requirement is to count the number of IPs visited daily. Although there is data in the data table, for demonstration purposes, create a new listener statistics.
Record IP
This article introduces the implementation of events/listeners and expands on this basis.
Register a new listener and add CreateUserIpLog in the app/Providers/EventServiceProvider.php file
/** * The event listener mappings for the application. * * @var array */ protected $listen = [ Registered::class => [ SendEmailVerificationNotification::class, ], 'App\Events\UserBrowse' => [ 'App\Listeners\CreateBrowseLog',// 用户访问记录 'App\Listeners\CreateUserIpLog',// 用户 IP 记录 ], ];
After the addition is completed, execute php artisan event:generate
to create Okapp/Listeners/CreateUserIpLog.php
file;
- In the new listener, record the user's IP and use Redis's Set data type to record, the code is as follows
/** * Handle the event. * 记录用户 IP * @param UserBrowse $event * @return void */ public function handle(UserBrowse $event) { $redis = Redis::connection('cache'); $redisKey = 'user_ip:' . Carbon::today()->format('Y-m-d'); $isExists = $redis->exists($redisKey); $redis->sadd($redisKey, $event->ip_addr); if (!$isExists) { // key 不存在,说明是当天第一次存储,设置过期时间三天 $redis->expire($redisKey, 259200); } }
Statistical access
The user’s IP is recorded above, and then the statistical code is written
- Create a new task
php artisan make:command CountIpDay
, created a newapp/Console/Commands/CountIpDay.php
file; - Set signature
protected $signature = 'countIp:day';
and descriptionprotected $description = 'Statistics of daily access IP';
- Write code in the
handle
method, which can also be used inkernel.php
emailOutputTo
Method to send email
/** * Execute the console command. * * @return mixed */ public function handle() { $redis = Redis::connection('cache'); $yesterday = Carbon::yesterday()->format('Y-m-d'); $redisKey = 'user_ip:' . $yesterday; $data = $yesterday . ' 访问 IP 总数为 ' . $redis->scard($redisKey); // 发送邮件 Mail::to(env('ADMIN_EMAIL'))->send(new SendSystemInfo($data)); }
Set task scheduling
- Edit
app/Console/Kernel.php
's$commands
/** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ \App\Console\Commands\CountIpDay::class, ];
- Set a scheduled task in the
schedule
method, and the execution time is one o'clock in the morning every day
/** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { $schedule->command('countIp:day')->dailyAt('1:00'); }finally adds a scheduled task in Linux and executes it once every minute
artisan schedule:run
, as follows* * * * * /you_php you_path/artisan schedule:run >> / dev/null 2>&1
The above is the detailed content of Introduction to laravel task scheduling (with code). For more information, please follow other related articles on the PHP Chinese website!

What new features and best practices does Laravel's migration system offer in the latest version? 1. Added nullableMorphs() for polymorphic relationships. 2. The after() method is introduced to specify the column order. 3. Emphasize handling of foreign key constraints to avoid orphaned records. 4. It is recommended to optimize performance, such as adding indexes appropriately. 5. Advocate the idempotence of migration and the use of descriptive names.

Laravel10,releasedinFebruary2023,isthelatestLTSversion,supportedforthreeyears.ItrequiresPHP8.1 ,enhancesLaravelPennantforfeatureflags,improveserrorhandling,refinesdocumentation,andoptimizesperformance,particularlyinEloquentORM.

Laravel's latest version introduces multiple new features: 1. LaravelPennant is used to manage function flags, allowing new features to be released in stages; 2. LaravelReverb simplifies the implementation of real-time functions, such as real-time comments; 3. LaravelVite accelerates the front-end construction process; 4. The new model factory system enhances the creation of test data; 5. Improves the error handling mechanism and provides more flexible error page customization options.

Softleteinelelavelisling -Memptry-braceChortsDevetus -TeedeecetovedinglyDeveledTeecetteecedelave

Laravel10.xisthecurrentversion,offeringnewfeatureslikeenumsupportinEloquentmodelsandimprovedroutemodelbindingwithenums.Theseupdatesenhancecodereadabilityandsecurity,butrequirecarefulplanningandincrementalimplementationforasuccessfulupgrade.

LaravelmigrationsstreamlinedatabasemanagementbyallowingschemachangestobedefinedinPHPcode,whichcanbeversion-controlledandshared.Here'showtousethem:1)Createmigrationclassestodefineoperationslikecreatingormodifyingtables.2)Usethe'phpartisanmigrate'comma

To find the latest version of Laravel, you can visit the official website laravel.com and click the "Docs" button in the upper right corner, or use the Composer command "composershowlaravel/framework|grepversions". Staying updated can help improve project security and performance, but the impact on existing projects needs to be considered.

YoushouldupdatetothelatestLaravelversionforperformanceimprovements,enhancedsecurity,newfeatures,bettercommunitysupport,andlong-termmaintenance.1)Performance:Laravel9'sEloquentORMoptimizationsenhanceapplicationspeed.2)Security:Laravel8introducedbetter


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
