Skip to main content
  1. All Posts/

dispatcher

Tools PHP

Dispatcher

Dispatcher allows you to schedule your artisan commands within your Laravel project, eliminating the need to touch the crontab when deploying. It also allows commands to run per environment and keeps your scheduling logic where it should be, in your version control.

use IndatusDispatcherSchedulingScheduledCommand;
use IndatusDispatcherSchedulingSchedulable;
use IndatusDispatcherDriversDateTimeScheduler;

class MyCommand extends ScheduledCommand {
	public function schedule(Schedulable $scheduler)
	{
        //every day at 4:17am
        return $scheduler
            ->daily()
            ->hours(4)
            ->minutes(17);
    }
}

README Contents


## Features

  • Schedule artisan commands to run automatically
  • Scheduling is maintained within your version control system
  • Single source of truth for when and where commands run
  • Schedule commands to run with arguments and options
  • Run commands as other users
  • Run commands in certain environments
  • Use custom drivers for custom scheduling contexts


## Tutorial
By Ben Kuhl at the Laravel Louisville meetup (@lurvul): VideoSlides
By Jefferey Way at Laracasts: Recurring Tasks the Laravel Way

## Installation

NOTICE: Laravel 5 now includes scheduling out of the box. This package will no longer be maintained for Laravel 5 and above

Requirements
1.4.*
2.*

Laravel
4.1/4.2
5.x

PHP
5.3+
5.4+

HHVM
3.3+
3.3+

Install with Composer…
~1.4
~2.0@dev

If you’re using Laravel 4 view the readme in the 1.4 branch

Add this line to the providers array in your config/app.php file :

        'IndatusDispatcherServiceProvider',

Add the following to your root Crontab (via sudo crontab -e):

* * * * * php /path/to/artisan scheduled:run 1>> /dev/null 2>&1

If you are adding this to /etc/cron.d you’ll need to specify a user immediately after * * * * *.

You may add this to any user’s Crontab, but only the root crontab can run commands as other users.


### Upgrading from 1.4 to 2.0
In all scheduled commands…

  • Replace use IndatusDispatcherDriversCronScheduler with use IndatusDispatcherDriversDateTimeScheduler
  • Replaced uses of Scheduler::[DAY_OF_WEEK] with Day::[DAY_OF_WEEK] and Scheduler::[MONTH_OF_YEAR] with Month::[MONTH_OF_YEAR]
  • executable config option has been removed. Dispatcher now inherits the path to the binary that was initially used to run scheduled:run


## 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

If commands are not visible via php artisan then they cannot be scheduled.

### Generating New Scheduled Commands
Use php artisan scheduled:make to generate a new scheduled command, the same way you would use artisan’s command:make. Then register your command with Laravel.

### Scheduling Existing Commands
You may either implement IndatusDispatcherSchedulingScheduledCommandInterface or follow the below steps.

<ol dir="auto">
  <li>
    Add use statements to your command. If you&#8217;re using a custom driver you will use a different <code>Scheduler</code> class.
  </li>
</ol>

<pre>use IndatusDispatcherSchedulingScheduledCommand;

use IndatusDispatcherSchedulingSchedulable; use IndatusDispatcherDriversDateTimeScheduler;

<ol start="2" dir="auto">
  <li>
    Extend <code>IndatusDispatcherSchedulingScheduledCommand</code>
  </li>
  <li>
    Implement schedule():
  </li>
</ol>

<pre>	/**
 * When a command should run
 *
 * @param Scheduler $scheduler
 *
 * @return Scheduler
 */
public function schedule(Schedulable $scheduler)
{
	return $scheduler;
}</pre>

<p>
  </a>For details and examples on how to schedule, see the <a rel="nofollow noopener" target="_blank" href="#datetime">DateTime Driver</a>.<br /> <a rel="nofollow noopener" target="_blank" name="user-content-commands-as-users"><br /> ### Running Commands As Users<br /> You may override <code>user()</code> to run a given artisan command as a specific user. Ensure your <code>scheduled:run</code> artisan command is running as root.</p> 
  
  <pre>    public function user()
{
    return 'backup';
}</pre>
  
  <blockquote>
    <p>
      This feature may not be supported by all drivers.
    </p>
  </blockquote>
  
  <p>
    </a><a rel="nofollow noopener" target="_blank" name="user-content-environment-commands"><br /> ### Environment-Specific Commands<br /> You may override <code>environment()</code> to ensure your command is only scheduled in specific environments. It should provide a single environment or an array of environments.</p> 
    
    <pre>    public function environment()
{
    return ['development','staging'];
}</pre>
    
    <p>
      </a><a rel="nofollow noopener" target="_blank" name="user-content-maintenance-mode"><br /> ### Maintenance Mode<br /> By default, cron commands will not run when application is in Maintenance Mode. This will prevent all sorts of weird output that might occur if a cron command is run while you are migrating a database or doing a composer update.<br /> You may override <code>runInMaintenanceMode()</code> to force your command to still be run while the application is in maintenance mode.</p> 
      
      <pre>    public function runInMaintenanceMode()
{
    return true;
}</pre>
      
      <p>
        </a><a rel="nofollow noopener" target="_blank" name="user-content-advanced-scheduling"><br /> ### Advanced scheduling<br /> You may schedule a given command to to run at multiple times by <code>schedule()</code> returning multiple <code>Schedulable</code> instances.</p> 
        
        <pre>	public function schedule(Schedulable $scheduler)
{
    return [
        // 5am Mon-Fri
        $scheduler-&gt;everyWeekday()-&gt;hours(5),

        // 2am every Saturday
        App::make(get_class($scheduler))
            -&gt;daysOfTheWeek(Scheduler::SATURDAY)
            -&gt;hours(2)
    ];
}</pre>
        
        <p>
          You may also schedule a command to run with arguments and options.
        </p>
        
        <pre>	public function schedule(Schedulable $scheduler)
{
	return [
        // equivalent to: php /path/to/artisan command:name /path/to/file
        $scheduler-&gt;args(['/path/to/file'])
            -&gt;everyWeekday()
            -&gt;hours(5),

        // equivalent to: php /path/to/artisan command:name /path/to/file --force --toDelete="expired" --exclude="admins" --exclude="developers"
        $scheduler-&gt;args(['/path/to/file'])
            -&gt;opts([
                'force',
                'toDelete' =&gt; 'expired',
                'exclude' =&gt; [
                    'admins',
                    'developers'
                ]
            ])
            -&gt;daysOfTheMonth([1, 15])
            -&gt;hours(2)
    ];
}</pre>
        
        <blockquote>
          <p>
            NOTE: Both <code>args()</code> and <code>opts()</code>, whichever is called first, will internally create a new <code>Schedulable</code> instance for you so you don&#8217;t need to <code>App::make()</code>.
          </p>
        </blockquote>
        
        <p>
          </a><a rel="nofollow noopener" target="_blank" name="user-content-drivers"><br /> ## Drivers<br /> </a>Drivers provide the ability to add additional context to your scheduling. <a rel="nofollow noopener" target="_blank" href="#custom-drivers">Building custom drivers</a> is a great way to customize this context to your application&#8217;s needs.<br /> <a rel="nofollow noopener" target="_blank" name="user-content-datetime"><br /> ### DateTime (Default)<br /> Examples of how to schedule:</p> 
          
          <pre>	public function schedule(Schedulable $scheduler)
{
    //every day at 4:17am
    return $scheduler-&gt;daily()-&gt;hours(4)-&gt;minutes(17);
}</pre>
          
          <pre>	public function schedule(Schedulable $scheduler)
{
    //every Tuesday/Thursday at 5:03am
    return $scheduler-&gt;daysOfTheWeek([
            Scheduler::TUESDAY,
            Scheduler::THURSDAY
        ])-&gt;hours(5)-&gt;minutes(3);
}</pre>
          
          <pre>	public function schedule(Schedulable $scheduler)
{
    //the second and third Tuesday of every month at 12am
    return $scheduler-&gt;monthly()-&gt;week([2, 3])-&gt;daysOfTheWeek(Day::TUESDAY);
}</pre>
          
          <p>
            </a><a rel="nofollow noopener" target="_blank" name="user-content-custom-drivers"><br /> ## Custom Drivers<br /> Custom drivers allow you to provide application context within scheduling. For example, an education-based application may contain scheduling methods like <code>inServiceDays()</code>, <code>springBreak()</code> and <code>christmasBreak()</code> where commands are run or don&#8217;t run during those times.<br /> Create a packagepath such as <code>MyAppScheduleDriver</code> and create two classes:</p> 
            
            <ul dir="auto">
              <li>
                <code>Scheduler</code> that <code>implements IndatusDispatcherSchedulingSchedulable</code>. This class should provide a useful interface for programmers to schedule their commands.
              </li>
              <li>
                <code>ScheduleService</code> that <code>extends IndatusDispatcherServicesScheduleService</code>. This class contains logic on how to determine if a command is due to&#8230;</a></p>