Tuesday, March 28, 2017

Laravel how to create a custom Artisan Console Command

My project need a report function which run every 30 minutes.
And, here is my solution for this task: Using Artisan Console Command, combine with Linux's crontab.

1. Prepare:
- Set php environment (optional)
- Laravel 5.x
- Allow your account can run "crontab" function

2. Create a custom Console command:   GeneralReport
cd /your/project/path/
php artisan make:command GeneralReportCommand

This command will generate a class with name "GeneralReportCommand" in folder /your/project/path/app/Console/Commands/



3. Configure some importance variable in the new class:
- Command name and parameters when run command. In this example, I declare the name is "report:general" and 2 optional parameters: start_date, end_date
protected $signature = 'report:general {start_date?} {end_date?}';

- Handle command:
public function handle(){    
    // report  
    if ($this->argument('start_date')) {        
        $startDate = $this->argument('start_date') . " 00:00:00";        
        $endDate = $this->argument('end_date') . " 23:59:59";
        $period = new \DatePeriod(            
            new \DateTime($startDate),            
            new \DateInterval('P1D'),            
            new \DateTime($endDate)        
        );
        
        foreach ($period as $date) {            
            $reportDate = $date->format("Y-m-d");            
            self::doReport($reportDate);        
        }    
    } // End if    
        else {        
        $reportDate = date('Y-m-d');        
        self::doReport($reportDate);    
    }
}

4. How to Run the command? 
Open your terminal then run:
cd /your/project/path/
php artisan report:general "2017-03-20" "2017-03-23"
5. Configure crontab to run every 30 minutes
crontab -e
*/30 * * * * /u01/ottportal/env/php/bin/php /u01/ottportal/cms/artisan report:general 

Note: You may wonder why don't have any parameter? Because they're optional. In this task, if don't set any parameter, I will set report date is current date :)

No comments:

Post a Comment