Showing posts with label Laravel. Show all posts
Showing posts with label Laravel. Show all posts

Friday, June 14, 2019

Laravel 4 Scheduller with dispatcher


Dispatcher is a Laravel artisan command scheduling tool used to schedule artisan commands within your project so you don't need to touch your crontab when deploying.

For Futher Information go to this link Dispatcher.


  • Do you hate to touch crontab to add scheduller in laravel?
  • Do you hate with all crontab configuration when add scheduller in different servers?
Congratulations,  Laravel has package to handle this problem using Dispatcher. Everthing become simple and easy with this package. Doubt? Here we go!

Tool Kit

  • PHP 5.3+ or HHVM
  • Laravel 4

Configurations

In your application add this to your "require" :{} composer.json

    "indatus/dispatcher": "1.4.*@dev"

remember to do composer update.
In your app/config/app.php providers array add this line:

'Indatus\Dispatcher\ServiceProvider',

Usage

scheduled
  scheduled:make              Create a new scheduled artisan command
  scheduled:run               Run scheduled commands
  scheduled:summary           View a summary of all scheduled artisan commands

Build scheduled command

php artisan scheduled:make yourCommands

Register scheduled command

In Your app/start/artisan.php add this line depend on Your Command :


Artisan::add(new yourCommands);

Scripting

Go to your command app/command/yourCommands and change 

// my artisan command will be php artisan cron:mycommands
protected $name = 'cron:yourCommands';

// Configure this functions to change schedule time
public function schedule(Schedulable $scheduler)
{
  // Change this function to change time
  return $scheduler->daily();
}

This is Scheduler Changes time function example list:

//every day at 4:17am
return $scheduler->daily()->hours(4)->minutes(17);

//every Monday/Friday at 8:30am
return $scheduler->daysOfTheWeek([
                Scheduler::MONDAY,
                Scheduler::FRIDAY
            ])->hours(8)->minutes(30);

// Using Raw Commands
//every other day at 1:59am, 13:59pm and 23:59pm
return $scheduler->setSchedule(59, [1,13,23], '*/2', '*', '*');

// Every minutes
return $scheduler->everyMinutes();

// Every 20 minutes
return $scheduler->everyMinutes(10);

// Every hours
return $scheduler->everyHours();

Cron Setup

In console add

crontab -e
* * * * * php {{ path to your app}}/artisan scheduled:run 1>> /dev/null 2>&1

Debugging

If your cron not running check this

// Via console, check your mcrypt
php -i | mcrypt.

// Via console
php artisan scheduled:run --debug 
backup:avatars: No schedules were due
     command:name: No schedules were due
     myTestCommand:name: No schedules were due
     cache:clean: /usr/bin/env php /Users/myUser/myApp/artisan cache:clean > /dev/null &
     mail:subscribers: /usr/bin/env php /Users/myUser/myApp/artisan mail:subscribers > /dev/null &

// Via Console
php artisan scheduled:summary
//It works if output something like this:
+----------------+------------------+-----------+--------+------+--------------+-------+-------------+--------+
| Environment(s) | Name             | Args/Opts | Minute | Hour | Day of Month | Month | Day of Week | Run as |
+----------------+------------------+-----------+--------+------+--------------+-------+-------------+--------+
| *              | schedule:test    |           | */5    | *    | *            | *     | *           |        |
+----------------+------------------+-----------+--------+------+--------------+-------+-------------+--------+

Share:

Tuesday, May 28, 2019

Laravel 4 Queue with Beanstalk and Supervisor



Queue  is great tools in laravel for implementing delayed job. Queue allowing system to put task in background so it can become faster and make users skip waiting until tasks is finished.
Queue can be implemented to handle big process such as generating reports, image processing, sending email, or even heavy CRUD process.

Tool Kit

Configuration

Installing Queue

In your application add this to your "require" :{} composer.json

    "pda/pheanstalk": "2.0.*"

Scripting

You can create new class or use controller/model/any class to execute function with Queue. Below is function in controller class executed by Queue.

<?php

class ReportsController extends \BaseController {
  function fire($job,$data){
    //Function Process
  }
}

To execute this method with queue use this command

Queue::push('ReportsController', $data);

Other alternative is to execute function without fire method

<?php

class ReportsController extends \BaseController {
  function generateReport($job,$data){
    //Function Process
  }
}

To execute this method with queue use this command

Queue::push('ReportsController@generateReport', $data);

Queue::push() command can be use in Route, Controller, or even Command.

Running Queue

To running Queue we need Beanstalk as a worker. To activate beanstalk running this command in console

  // To fire last job
  php artisan queue:work

  // To fire running job and listen it
  php artisan queue:listen

  // add listener with flag (you can choose or implement all of this)
  php artisan queue:work --timeout=0 --queue="default" --delay=0 --memory=128 --sleep=3 --tries=0

Install and Configure Beanstalk

Install Beanstalk

sudo apt-get update
// Install in Debian or ubuntu
sudo apt-get install beanstalkd

Configure Beanstalk

sudo nano /etc/default/beanstalkd

// Add or uncomment this line
START yes

Start Beanstalk
sudo service beanstalkd start

Configure Beanstalk in Our Laravel App

Set default queue in app to Beanstalk. Go to app/config/queue.php

// Change This
'default' => 'beanstalkd',

// This is default beanstalk configurations
'connections' => array(

    'beanstalkd' => array(
        'driver' => 'beanstalkd',
        'host'   => 'localhost', 
        'queue'  => 'default',
        'ttr'    => 60,
    ),

),

Supervisor

We use php artisan queue:work or php artisan queue:work as listener, but we know that impossible for us to running this command every time we push job to Queue or when we start servers.

To overcome this we use Supervisor to listen all of active worker. Supervisor will listen all of our queue:work --daemon and restart it if failed.

Install Supervisor


// Install Supervisor in Debian or ubuntu
sudo apt-get install supervisor

// Adding configurations
sudo nano /etc/supervisor/conf.d/reportqueue.conf

[program:reportqueue]
command=php artisan queue:work --daemon --env=your_environment
directory=/path/to/MYAPP
stdout_logfile=/path/to/MYAPP/app/storage/logs/myqueue_supervisord.log
redirect_stderr=true
autostart=true
autorestart=true

Add Configuration to Supervisor


sudo supervisorctl
reread # Tell supervisord to check for new items in /etc/supervisor/conf.d/
add reportqueue       # Add reportqueue process to Supervisord
start reportqueue     # Let's Rock

Check Supervisor


// In Console
ps aux | grep php

# You should see some output similarish this:
php artisan queue:work --daemon --env=your_environment
sh -c php artisan queue:work  --queue="default" --delay=0 --memory=128 --sleep --env=your_environment
php artisan queue:work --queue=default --delay=0 --memory=128 --sleep --env=your_environment
Share:

Friday, October 24, 2014

Build Background Job in Laravel Using Cron Job

Cron Job with Laravel running with Artisan Command. So we have to make command using Artisan.

Generate Class.
php artisan command:make FooCommand 
php artisan command:make [[your command]]
This command will generate a class in app/commands.

Write Your Function
Write your functions in your generated command fire() method.

Register Command
Write: Artisan::add(new [[your command]]);
In app/start/artisan.php

Runs Cron Job
Write in terminal : crontab -e
Write:
* * * * * php [[path to application]]/[[your application]]/artisan background:process
* * * * * : it means this cron job will be executed every minutes
Share: