Git Product home page Git Product logo

dispatcher's Introduction

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 Indatus\Dispatcher\Scheduling\ScheduledCommand;
use Indatus\Dispatcher\Scheduling\Schedulable;
use Indatus\Dispatcher\Drivers\DateTime\Scheduler;

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

Latest Stable Version Total Downloads Build Status Code Coverage Scrutinizer Code Quality

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): Video - Slides

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 :

        'Indatus\Dispatcher\ServiceProvider',

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 Indatus\Dispatcher\Drivers\Cron\Scheduler with use Indatus\Dispatcher\Drivers\DateTime\Scheduler
  • 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 \Indatus\Dispatcher\Scheduling\ScheduledCommandInterface or follow the below steps.

  1. Add use statements to your command. If you're using a custom driver you will use a different Scheduler class.
use Indatus\Dispatcher\Scheduling\ScheduledCommand;
use Indatus\Dispatcher\Scheduling\Schedulable;
use Indatus\Dispatcher\Drivers\DateTime\Scheduler;
  1. Extend \Indatus\Dispatcher\Scheduling\ScheduledCommand
  2. Implement schedule():
	/**
	 * When a command should run
	 *
	 * @param Scheduler $scheduler
	 *
	 * @return Scheduler
	 */
	public function schedule(Schedulable $scheduler)
	{
		return $scheduler;
    }

For details and examples on how to schedule, see the DateTime Driver.

### Running Commands As Users

You may override user() to run a given artisan command as a specific user. Ensure your scheduled:run artisan command is running as root.

    public function user()
    {
        return 'backup';
    }

This feature may not be supported by all drivers.

### Environment-Specific Commands

You may override environment() to ensure your command is only scheduled in specific environments. It should provide a single environment or an array of environments.

    public function environment()
    {
        return ['development','staging'];
    }
### Maintenance Mode

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.

You may override runInMaintenanceMode() to force your command to still be run while the application is in maintenance mode.

    public function runInMaintenanceMode()
    {
        return true;
    }
### Advanced scheduling

You may schedule a given command to to run at multiple times by schedule() returning multiple Schedulable instances.

	public function schedule(Schedulable $scheduler)
	{
        return [
            // 5am Mon-Fri
            $scheduler->everyWeekday()->hours(5),

            // 2am every Saturday
            App::make(get_class($scheduler))
                ->daysOfTheWeek(Scheduler::SATURDAY)
                ->hours(2)
        ];
    }

You may also schedule a command to run with arguments and options.

	public function schedule(Schedulable $scheduler)
	{
		return [
            // equivalent to: php /path/to/artisan command:name /path/to/file
            $scheduler->args(['/path/to/file'])
                ->everyWeekday()
                ->hours(5),

            // equivalent to: php /path/to/artisan command:name /path/to/file --force --toDelete="expired" --exclude="admins" --exclude="developers"
            $scheduler->args(['/path/to/file'])
                ->opts([
                    'force',
                    'toDelete' => 'expired',
                    'exclude' => [
                        'admins',
                        'developers'
                    ]
                ])
                ->daysOfTheMonth([1, 15])
                ->hours(2)
        ];
	}

NOTE: Both args() and opts(), whichever is called first, will internally create a new Schedulable instance for you so you don't need to App::make().

## Drivers

Drivers provide the ability to add additional context to your scheduling. Building custom drivers is a great way to customize this context to your application's needs.

### DateTime (Default)

Examples of how to schedule:

	public function schedule(Schedulable $scheduler)
	{
        //every day at 4:17am
        return $scheduler->daily()->hours(4)->minutes(17);
    }
	public function schedule(Schedulable $scheduler)
	{
        //every Tuesday/Thursday at 5:03am
        return $scheduler->daysOfTheWeek([
                Scheduler::TUESDAY,
                Scheduler::THURSDAY
            ])->hours(5)->minutes(3);
    }
	public function schedule(Schedulable $scheduler)
	{
        //the second and third Tuesday of every month at 12am
        return $scheduler->monthly()->week([2, 3])->daysOfTheWeek(Day::TUESDAY);
    }
## Custom Drivers

Custom drivers allow you to provide application context within scheduling. For example, an education-based application may contain scheduling methods like inServiceDays(), springBreak() and christmasBreak() where commands are run or don't run during those times.

Create a packagepath such as \MyApp\ScheduleDriver\ and create two classes:

  • Scheduler that implements Indatus\Dispatcher\Scheduling\Schedulable. This class should provide a useful interface for programmers to schedule their commands.
  • ScheduleService that extends \Indatus\Dispatcher\Services\ScheduleService. This class contains logic on how to determine if a command is due to run.

Publish the configs using php artisan config:publish indatus/dispatcher. Then update your driver configuration to reference the package in which these 2 classes are included (do not include a trailing slash):

    'driver' => '\MyApp\ScheduleDriver'
## FAQ

I need to deploy to multiple servers representing a single environment. How can I be sure my command is only run by a single server and not run on each server?

Schedule scheduled:run to run every minute with rcron:

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

Why are my commands not running when I've scheduled them correctly? I'm also not seeing any error output

  1. Verify that mcrypt is installed and working correctly via the command php -i | mcrypt.

  2. Utilizing php artisan scheduled:run --debug will tell you why they're not running. If you do not see your command listed here then it is not set up correctly.

Example:

$ php artisan scheduled:run --debug                                                                                        
Running commands...
     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 &

I have commands that extend ScheduledCommand but why don't they appear in when I run scheduled:summary?

Commands that are disabled will not appear here. Check and be sure isEnabled() returns true on those commands.

dispatcher's People

Contributors

bkuhl avatar crynobone avatar developeryamhi avatar djekl avatar grahamcampbell avatar nbourguig avatar opb avatar schnoop avatar valorin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dispatcher's Issues

PHP 5.3 support?

Hi,

is there any reason that your package will not run under PHP 5.3?

Greetings.

Thorsten

Command executing when not scheduled to do so...

I have a command in my laravel project that is executing at midnight when it is not scheduled to do so. Does anyone know why this would happen?

Here's my "schedule" function:

public function schedule(Schedulable $scheduler)
{
return $scheduler->daily()->hours(7);
}

...And here's the log output for today:

[2014-10-17 00:00:19] production.INFO: Market Report for October, 2014 : TO USER #101 [] []
[2014-10-17 07:00:03] production.INFO: Market Report for October, 2014 : TO USER #101 [] []

Not to complicate things, but the "every minute" cron is also setup to run as "root" (as suggested in the docs), and that causes other errors to occur when apache (via Laravel) tries to write to the log file later on.

ANY help, suggestions or advice would be much appreciated.

Thanks everyone!

  • Hugh

Command executing when not scheduled to do so...

I have a command in my laravel project that is executing at midnight when it is not scheduled to do so. Does anyone know why this would happen?

Here's my "schedule" function:

public function schedule(Schedulable $scheduler)
{
return $scheduler->daily()->hours(7);
}

...And here's the log output for today:

[2014-10-17 00:00:19] production.INFO: Market Report for October, 2014 : TO USER [email protected] [] []
[2014-10-17 07:00:03] production.INFO: Market Report for October, 2014 : TO USER [email protected] [] []

Not to complicate things, but the "every minute" cron is also setup to run as "root" (as suggested in the docs), and that seems to cause other errors to occur when apache (via Laravel) tries to write to the log file later on.

ANY help, suggestions or advice would be much appreciated.

Thanks everyone!

  • Hugh

syntax error when running in Windows

Hi,

i try to use this on a windows environment and get an error "syntax error" when use artisan scheduled:run.

I solve this by change the function getRunCommand in CommandService.php

        $platform = App::make('Indatus\Dispatcher\Platform');
        $commandPieces[] = $platform->isWindows() ? '' : '&';                    //run in background
        $commandPieces[] = $platform->isWindows() ? '>NUL' : '> /dev/null 2>&1'; //don't show output, errors can be viewed in the Laravel log

is there a better way?

Bye, René

Something missing from the documentation

Either this is missing from the documentation, or I am just not reading it properly, but it is not clear to me how schedules get linked to existing commands.

Is the approach to take an existing command, then turn it into a command that extends ScheduledCommand rather than just Command?

Or is the approach to create a new command for each schedule you need, and use that command to call up an existing command, passing it any additional parameters and options?

So if I have command X that I wish to schedule for each minute on dev, and for each hour on production, would I need to create scheduled command (say) X_DEV and another X_PROD, each with their own schedules and each linked to the appropriate environment ('dev' and '')? If this is how it works, what stops X_DEV and X_PROD (or maybe scheduled:X) being run as command-line artisan commands?

Or maybe a single command that I want to run on both environments using different schedules, would check App::environment() before returning the schedule they intend to run to?

Thanks. Hopefully I'm not being too dumb, but the documentation kind of jumps straight into scheduling a single command, without showing how it fits into the overall environment.

[Request] Option to provide path to PHP or HHVM

I recently ran into some issues when trying to make Dispatcher work on one of my servers.
The default php command called by Dispatcher was not initializing my environment properly, so the artisan command that I had setup in the scheduler was not being called properly. I kept getting an error saying that the command was not available in the used namespace; Even when declaring the command without namespace, there was an error saying that the command did not exist.

The command was running fine when not executed via Dispatcher, so after some research and trial and error, I updated the the php command to use php-cli in the CommandService.php file and that fixed the issue.

I had tried to setup the scheduled:run cron using php-cli, but the final call to my scheduled command was always done with the default php, so it was failing.

It would be great if we could specify what program should be used for the calls, the same way that we can specify the path to artisan, arguments and options, without having to update the source Dispatcher code.

Thanks

Cannot get Laracast example to fire MAC OSX Mavricks

Hi,

I create the cron command file and start crontab. But it never fires. If I enter the command manually, it works. When do crontab -l it shows the job????

  • * * * * php /Users/jimm/WebProjects/laravel42/artisan scheduled:run 1>> /dev/null 2>&1

Natively Run Commands w/ Artisan::call vs exec()

Right now, Dispatcher runs commands via exec().

I can think of a few reasons to run commands via exec() over Artisan::call(), but not many, especially given the issues this causes, mostly defining an external executable (PHP_BINARY should be used at if it's available on the newer versions of PHP) and running into situations where arguments/options aren't properly passed.

Would you consider adding a config option to allow for native Artisan calls?

Develop Branch???

Why is there a develop branch? Does it not make sense to put everything in the master, and alias the master to 1.4-dev?

php artisan scheduled:summary

HI @bkuhl I am not sure what I am doing wrong, but when I do a php artisan scheduled:summary I do not see any of my commands. I followed the simple installation steps, doing a composer requre, added service provider to my app/config/app.php. I then did a php artisan scheduled:make and it does place a file in my app/commands/testCommand.php.

Is there anything you can think of what is required next to get the list of jobs to show up?

Thanks!
Adam

Artisan error

I've scoured the README over and over again, but I can't get a command to work. I took an existing artisan command and moved it over to a scheduled one using php artisan scheduled:make, used the examples exactly, but get the following error after trying to run php artisan:

Declaration of MyCommand::schedule() must be compatible with Indatus\Dispatcher\ScheduledCommandInterface::schedule(Indatus\Dispatcher\Schedulable $scheduler) in /path/to/my/app/commands/MyCommand.php on line 8

Line 8 is the class declaration, exactly as generated:

class MyCommand extends ScheduledCommand {

And I've registered the command in my artisan.php file.

L5 support broken?

Hi! Just got following error when tried to execute php artisan scheduled:run or scheduled:summary
Latest laravel from "laravel/framework": "dev-master",
dispatcher from "indatus/dispatcher": "dev-master",

Fatal error: Call to undefined method App\Console\Kernel::all() in /home/vagrant/Code/gas/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 205

Call Stack:
0.0005 223472 1. {main}() /home/vagrant/Code/gas/artisan:0
0.1878 2488256 2. App\Console\Kernel->handle() /home/vagrant/Code/gas/artisan:46
0.1878 2488320 3. Illuminate\Foundation\Console\Kernel->handle() /home/vagrant/Code/gas/app/Console/Kernel.php:28
1.9346 14466744 4. Symfony\Component\Console\Application->run() /home/vagrant/Code/gas/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:69
1.9347 14467856 5. Symfony\Component\Console\Application->doRun() /home/vagrant/Code/gas/vendor/symfony/console/Symfony/Component/Console/Application.php:126
1.9348 14468776 6. Symfony\Component\Console\Application->doRunCommand() /home/vagrant/Code/gas/vendor/symfony/console/Symfony/Component/Console/Application.php:195
1.9348 14468944 7. Illuminate\Console\Command->run() /home/vagrant/Code/gas/vendor/symfony/console/Symfony/Component/Console/Application.php:874
1.9348 14469312 8. Symfony\Component\Console\Command\Command->run() /home/vagrant/Code/gas/vendor/laravel/framework/src/Illuminate/Console/Command.php:100
1.9350 14472848 9. Illuminate\Console\Command->execute() /home/vagrant/Code/gas/vendor/symfony/console/Symfony/Component/Console/Command/Command.php:252
1.9350 14472960 10. Indatus\Dispatcher\Commands\Run->fire() /home/vagrant/Code/gas/vendor/laravel/framework/src/Illuminate/Console/Command.php:112
1.9464 14491880 11. Indatus\Dispatcher\Services\CommandService->runDue() /home/vagrant/Code/gas/vendor/indatus/dispatcher/src/Indatus/Dispatcher/Commands/Run.php:77
1.9532 14500720 12. Indatus\Dispatcher\Services\ScheduleService->getQueue() /home/vagrant/Code/gas/vendor/indatus/dispatcher/src/Indatus/Dispatcher/Services/CommandService.php:42
1.9599 14507104 13. Indatus\Dispatcher\Services\ScheduleService->getScheduledCommands() /home/vagrant/Code/gas/vendor/indatus/dispatcher/src/Indatus/Dispatcher/Services/ScheduleService.php:61
1.9626 14515224 14. Illuminate\Support\Facades\Artisan::all() /home/vagrant/Code/gas/vendor/indatus/dispatcher/src/Indatus/Dispatcher/Services/ScheduleService.php:38
1.9626 14515408 15. Illuminate\Support\Facades\Facade::__callStatic() /home/vagrant/Code/gas/vendor/indatus/dispatcher/src/Indatus/Dispatcher/Services/ScheduleService.php:38

Avoid task overlapping

Is there a way to check if a task (e.g. Task A) is running so as to stop the other tasks (e.g. Task B, Task C) from running until Task A finishes???

Maintenance mode

I'm wondering if perhaps when the app is in "maintenance mode" that any attempts at running a cron should be blocked?

Currently I now have to put something like this in all my commands

    public function fire()
    {
        if (App::isDownForMaintenance())
        {
            echo 'In maintenance mode - no cron task was run.';
        }
        else
        {
            // do cron task
        }
    }

Otherwise there is a risk that if a cron task occurs during a Laravel upgrade, you'll get all sorts of weird output.

Although I can see that perhaps some people do what a cron to run, even if in maintenance mode, so perhaps it needs to be a configurable option? Perhaps even a flag in the command itself, so some crons run in maintenance mode, while others do not?

Happy to discuss - open to ideas/thoughts...

Way to pass flags or options to commands?

How would I schedule a command to be ran with certain command line flags or options? What if I want a command to run at different times with different flags/options set?

Sort schedule summary

Would be great to be able to sort the scheduled:summary by when it's going to run - like ascending on hour, minute, or even command name.

More than happy to help with a PR. Would the best place to start be within/around the printSummary()? I was thinking of sorting the before the first foreach loop on line #51

A quick hack for anyone interested in sorting by name is to just reorder the commands within the app/start/artisan.php file.

Thanks for this great package!

Composer fetching the wrong version

I tried to get the dev version running with laravel 5.
But the composer entry
"indatus/dispatcher": "dev-master"

still fetches version 1.4.1

Suggestions?

Unresolvable dependency resolving [Parameter #0 [ <required> $expression ]] in class Cron\CronExpression

Updates this morning seem to have caused:

vagrant@homestead:~/sites/sst$ artisan scheduled:run
exception 'Illuminate\Container\BindingResolutionException' with message 'Unresolvable dependency resolving [Parameter #0 [ $expression ]] in class Cron\CronExpression' in /home/vagrant/sites/sst/vendor/laravel/framework/src/Illuminate/Container/Container.php:841

I have updated my commands to "use Indatus\Dispatcher\Drivers\DateTime\Scheduler;".

Happy to investigate further myself if there's no quick fix!

--env Option Should Always Be Passed to Command

I'm running Dispatch with:

php artisan scheduled:run --env=qa

...however, it only pushes that env option along to my scheduled commands if I specify options to go along with my command via the opts() method.

For now, I'm just passing a blank array through to opts() which does the trick; however, scheduled:run should detect the forced env by default and relay it to other commands if it exists. No?

Adding --env option to the run command

Hi,

What will be the best way to set scheduled:run to a custom environment?
It is more of a feature request than an Issue.

If I am not mistaken most of Laravel's commands can accept the --env option.

There are no commands defined in the "scheduled" namespace.

I keep getting this error whenever I am running the

php artisan scheduled:summary

as well as the

 php artisan scheduled:run --debug

however when I run my scheduled command manually it runs.

here is the entire stack trace

production.ERROR: exception 'InvalidArgumentException' with message 'There are no commands defined in the "scheduled" namespace.' in /var/www/laravel/vendor/symfony/console/Symfony/Component/Console/Application.php:516
Stack trace:
#0 /var/www/laravel/vendor/symfony/console/Symfony/Component/Console/Application.php(550): Symfony\Component\Console\Application->findNamespace('scheduled')
#1 /var/www/laravel/vendor/symfony/console/Symfony/Component/Console/Application.php(190): Symfony\Component\Console\Application->find('scheduled:run')
#2 /var/www/laravel/vendor/symfony/console/Symfony/Component/Console/Application.php(124): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#3 /var/www/laravel/artisan(59): Symfony\Component\Console\Application->run()
#4 {main} [] []

Can you please let me know , what am I doing wrong here ? Any help would be highly appreciated as this is kinda urgent .

thanks .

exception 'InvalidArgumentException' with message 'There are no commands defined in the "xxx" namespace.'

I'm getting this error:

[2014-08-24 20:19:02] staging.ERROR: exception 'InvalidArgumentException' with message 'There are no commands defined in the "trusty" namespace.' in /home/trustywebapp/public_html/stagingtrusty/vendor/symfony/console/Symfony/Component/Console/Application.php:516
Stack trace:
#0 /home/trustywebapp/public_html/stagingtrusty/vendor/symfony/console/Symfony/Component/Console/Application.php(550): Symfony\Component\Console\Application->findNamespace('trusty')
#1 /home/trustywebapp/public_html/stagingtrusty/vendor/symfony/console/Symfony/Component/Console/Application.php(190): Symfony\Component\Console\Application->find('trusty:log')
#2 /home/trustywebapp/public_html/stagingtrusty/vendor/symfony/console/Symfony/Component/Console/Application.php(124): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#3 /home/trustywebapp/public_html/stagingtrusty/artisan(58): Symfony\Component\Console\Application->run()
#4 {main} [] []

This is what I put in the cpanel cron job:
php /home/trustywebapp/public_html/stagingtrusty/artisan scheduled:run 1>> /dev/null 2>&1

Pls help.

Old version of php-cli-tools causing errors

When running php artisan scheduled:summary I receive the following error:

{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException",
"message":"Call to undefined function cli\\posix_isatty()","file":
"\/var\/www\/vendor\/jlogsdon\/cli\/lib\/cli\/Streams.php","line":17}}{"error":
{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException",
"message":"Call to undefined function cli\\posix_isatty()",
"file":"\/var\/www\/vendor\/jlogsdon\/cli\/lib\/cli\/Streams.php","line":17}}

I've tracked the error to relating to jlogsdon/php-cli-tools/issues/27. If I manually apply that change to the files in the Vendor directory, it fixes the issue, but these changes will be overwritten by future composer update calls.

Is there anyway the composer.json file for Dispatcher can be updated to use "dev-master" instead of the "v0.9.4" tag (which is 9 months old now).

Ideally, it would be better if jlogsdon/php-cli-tools were to release a new tagged version but I'm not sure when that might happen.

I'm not sure what other information I can provide to help debug this issue, but let me know if you need me to find any software versions, etc.

Why do opts and args return a new instance?

I may not be familiar with the internal code of Dispatcher but this struck me as pretty weird:

Both args() and opts(), whichever is called first, will internally create a new Schedulable instance for you so you don't need to App::make().

This caused a major issue in our production environment where we were doing this:

return $scheduler->daily()->opts(['force']);

Since opts was called after daily instead of before it caused the command (which was an ES index rebuild) to run every minute instead of every day.

Asynchronous task

I tried 5 command for every minute. And each of them create a test file and sleep 30 seconds and then create second test file. I did this for try asynchronous. But all tasks run with synchron. Last command start (30+30+30+30) 2 minute after first trigger.

Then I'm look into codes for async. And edited CommandService class getRunCommand metod. (Found here http://www.php.net/manual/en/function.exec.php#86329)

// $commandPieces[] = '&';
$commandPieces[] = '> /dev/null &';

Now my tasks running async. Old code;

$commandPieces[] = '&';
$commandPieces[] = '> /dev/null 2>&1';

I think this command pieces broken. I'm tried this on debian 7.2 php5-cli

My test scheduled:summary results;

+----------------+---------------+-----------+--------+------+--------------+-------+-------------+--------+
| Environment(s) | Name          | Args/Opts | Minute | Hour | Day of Month | Month | Day of Week | Run as |
+----------------+---------------+-----------+--------+------+--------------+-------+-------------+--------+
| *              | command:name1 |           | *      | *    | *            | *     | *           |        |
| *              | command:name2 |           | *      | *    | *            | *     | *           |        |
| *              | command:name3 |           | *      | *    | *            | *     | *           |        |
| *              | command:name4 |           | *      | *    | *            | *     | *           |        |
| *              | command:name5 |           | *      | *    | *            | *     | *           |        |
+----------------+---------------+-----------+--------+------+--------------+-------+-------------+--------+

Related: #7

in laravel 4 showing 'Impossible CRON expression'

having same error in log file.
in schedule method it is -

return $scheduler->daily()->hours(4)->minutes(17);

on running following from shell it says 'No schedules were due'
scheduled:run --debug

Laravel 5.0

Using Laravel 4.3, when I run composer update I am presented with the following error:

PHP Fatal error: Class 'Illuminate\Foundation\Console\CommandMakeCommand' not found in /home/vagrant/Acme/vendor/indatus/dispatcher/src/Indatus/Dispatcher/Commands/Make.php on line 21

Fatal Error on Laravel 5

Error Output: PHP Fatal error: Class 'Illuminate\Foundation\Console\ConsoleMakeCommand'
not found in /indatus/dispatcher/src/Indatus/Dispatcher/Commands/Make.php on line 21

Jobs never run

I was really excited to see this come across Twitter today and started playing with it this afternoon. Unfortunately though, it doesn't look like it works at this point.

I created a simple Artisan task to add a message to the log file. I manually set up a cronjob to run every minute that called the specific command and it did as expected. Updated the job to run through Dispatcher and nothing ever happens. I can run the job manually, but no matter what I change (setting it to run every minute, setting it on a schedule, running the scheduled:run command manually, etc.), the job never runs.

Let me know what you need from me to help debug what might be going on. Thanks for the package!

[INFOREQ] Last Run Time

Is it possible to obtain a timestamp for the last time the scheduled task ran or do I need to store that somewhere myself?

1.4 Branch Proposal

Instead of having a 1.x, branch, I'd recommend just having a branch called 1.4. That way composer can automatically know that the branch represents 1.4.x-dev.

Including Dispatcher to Laravel-Project leads to error, when using "Artisan::call()"

In my project I use the construct of calling artisan commands from somewhere in my controllers. This works pretty well and is very convenient.
When I add dispatcher to my project (adding in composer.json, adding as ServiceProvider in app.php), every "Artisan::call()" leads to the error "Use of undefined constant STDOUT - assumed 'STDOUT'" (I don't even use any dispatcher functionality - I only installed it).

I reproduced the error by doing following:

  • Setting up a brand-new laravel project
  • adding a dummy command and putting the call "Artisan::call('test:command')" in the routes.php in the root-route
    ---> everything is fine
  • adding "indatus/dispatcher": "dev-master" to composer.json
    ---> everything is still fine
  • adding 'Indatus\Dispatcher\ServiceProvider' in app.php to the service-provider-array
    ---> error "Use of undefined constant STDOUT - assumed 'STDOUT'"

I am grateful for any information how to solve this.

Implement ScheduledCommandInterface as a trait

Just a suggestion that there be a trait version of the ScheduledCommandInterface.

So, say if someone's written a package that has a command you want to cron, you can subclass it and simply add that trait, rather than having to copy the class over.

Or, if there was another library that had, or if your project had an Illuminate\Console\Command subclass that you had to use for some reason, you could still easily use dispatcher by useing the trait.

I have two suggestions:

  • copy the the code in ScheduledCommand to ScheduledTrait. then whenever you change ScheduledCommand, update ScheduledTrait with the same changes (not ideal)
  • move the code in ScheduledCommand to ScheduledTrait, then make ScheduledCommand implement ScheduledTrait. That way you wouldn't have to make any changes in either of them, and it doesn't force people to use the trait. The downside of that is that it would break it for anyone using less than PHP 5.4 (which is a constraint in laravel 4.2, anyway, but not currently in dispatcher)

I'd be happy to submit a PR, but it's basically a copy and paste job ;)

No alias in crontab

Hi again,

In Unix system crontab "php .../artisan command" wont work. Need "/usr/bin/env php". Its defined in artisan.

Can you fix this? I'm editing your class for this in my vendor folder.

'ErrorException' with message 'Use of undefined constant STDOUT - assumed 'STDOUT'

I'm just setting up Dispatcher to take over from our cron jobs but I'm seeing this error in my logs whenever a scheduled command is meant to run. The command does not end up completing any of the tasks it was meant to.

Any ideas what could be going wrong here?

[2014-05-23 12:28:02] production.ERROR: exception 'ErrorException' with message 'Use of undefined constant STDOUT - assumed 'STDOUT'' in /home/laravel/vendor/wp-cli/php-cli-tools/lib/cli/Shell.php:51
Stack trace:
#0 /home/laravel/vendor/wp-cli/php-cli-tools/lib/cli/Shell.php(51): Illuminate\Exception\Handler->handleError(8, 'Use of undefine...', '/home/laravel/...', 51, Array)
#1 /home/laravel/vendor/wp-cli/php-cli-tools/lib/cli/Table.php(69): cli\Shell::isPiped()
#2 [internal function]: cli\Table->__construct(NULL, NULL, NULL)
#3 /home/laravel/bootstrap/compiled.php(254): ReflectionClass->newInstanceArgs(Array)
#4 /home/laravel/bootstrap/compiled.php(212): Illuminate\Container\Container->build('Indatus\\Diipatt...', Array)
#5 /home/laravel/bootstrap/compiled.php(586): Illuminate\Container\Container->make('Indatus\\Diipatt...', Array)
#6 /home/laravel/bootstrap/compiled.php(283): Illuminate\Foundation\Application->make('Indatus\\Diipatt...')
#7 /home/laravel/bootstrap/compiled.php(266): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter))
#8 /home/laravel/bootstrap/compiled.php(253): Illuminate\Container\Container->getDependencies(Array, Array)
#9 /home/laravel/bootstrap/compiled.php(212): Illuminate\Container\Container->build('Indatus\\Diipatt...', Array)
#10 /home/laravel/bootstrap/compiled.php(586): Illuminate\Container\Container->make('Indatus\\Diipatt...', Array)
#11 /home/laravel/bootstrap/compiled.php(3163): Illuminate\Foundation\Application->make('Indatus\\Diipatt...')
#12 /home/laravel/vendor/indatus/dispatcher/src/Indatus/Dispatcher/ConfigResolver.php(50): Illuminate\Support\Facades\Facade::__callStatic('make', Array)
#13 /home/laravel/vendor/indatus/dispatcher/src/Indatus/Dispatcher/ConfigResolver.php(50): Illuminate\Support\Facades\App::make('Indatus\\Diipatt...')
#14 /home/laravel/vendor/indatus/dispatcher/src/Indatus/Dispatcher/ServiceProvider.php(53): Indatus\Dispatcher\ConfigResolver->resolveServiceClass()
#15 /home/laravel/bootstrap/compiled.php(240): Indatus\Dispatcher\ServiceProvider->Indatus\Dispatcher\{closure}(Object(Illuminate\Foundation\Application), Array)
#16 /home/laravel/bootstrap/compiled.php(212): Illuminate\Container\Container->build(Object(Closure), Array)
#17 /home/laravel/bootstrap/compiled.php(586): Illuminate\Container\Container->make('Indatus\\Diipatt...', Array)
#18 /home/laravel/bootstrap/compiled.php(283): Illuminate\Foundation\Application->make('Indatus\\Diipatt...')
#19 /home/laravel/bootstrap/compiled.php(266): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter))
#20 /home/laravel/bootstrap/compiled.php(253): Illuminate\Container\Container->getDependencies(Array, Array)
#21 /home/laravel/bootstrap/compiled.php(212): Illuminate\Container\Container->build('Indatus\\Diipatt...', Array)
#22 /home/laravel/bootstrap/compiled.php(586): Illuminate\Container\Container->make('Indatus\\Diipatt...', Array)
#23 /home/laravel/bootstrap/compiled.php(3163): Illuminate\Foundation\Application->make('Indatus\\Diipatt...')
#24 /home/laravel/vendor/indatus/dispatcher/src/Indatus/Dispatcher/ServiceProvider.php(81): Illuminate\Support\Facades\Facade::__callStatic('make', Array)
#25 /home/laravel/vendor/indatus/dispatcher/src/Indatus/Dispatcher/ServiceProvider.php(81): Illuminate\Support\Facades\App::make('Indatus\\Diipatt...')
#26 /home/laravel/bootstrap/compiled.php(125): Indatus\Dispatcher\ServiceProvider->Indatus\Dispatcher\{closure}(Object(Illuminate\Foundation\Application))
#27 /home/laravel/bootstrap/compiled.php(240): Illuminate\Container\Container->Illuminate\Container\{closure}(Object(Illuminate\Foundation\Application), Array)
#28 /home/laravel/bootstrap/compiled.php(212): Illuminate\Container\Container->build(Object(Closure), Array)
#29 /home/laravel/bootstrap/compiled.php(586): Illuminate\Container\Container->make('command.schedul...', Array)
#30 /home/laravel/bootstrap/compiled.php(363): Illuminate\Foundation\Application->make('command.schedul...')
#31 /home/laravel/vendor/laravel/framework/src/Illuminate/Console/Application.php(134): Illuminate\Container\Container->offsetGet('command.schedul...')
#32 /home/laravel/vendor/laravel/framework/src/Illuminate/Console/Application.php(149): Illuminate\Console\Application->resolve('command.schedul...')
#33 /home/laravel/bootstrap/compiled.php(2912): Illuminate\Console\Application->resolveCommands(Array)
#34 [internal function]: Illuminate\Support\ServiceProvider->Illuminate\Support\{closure}(Object(Illuminate\Console\Application))
#35 /home/laravel/bootstrap/compiled.php(5805): call_user_func_array(Object(Closure), Array)
#36 /home/laravel/vendor/laravel/framework/src/Illuminate/Console/Application.php(71): Illuminate\Events\Dispatcher->fire('artisan.start', Array)
#37 /home/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Artisan.php(45): Illuminate\Console\Application->boot()
#38 /home/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Artisan.php(57): Illuminate\Foundation\Artisan->getArtisan()
#39 /home/laravel/bootstrap/compiled.php(3163): Illuminate\Foundation\Artisan->__call('add', Array)
#40 /home/laravel/bootstrap/compiled.php(3163): Illuminate\Foundation\Artisan->add(Object(Books\AmazonOfferCommand))
#41 /home/laravel/app/start/artisan.php(14): Illuminate\Support\Facades\Facade::__callStatic('add', Array)
#42 /home/laravel/app/start/artisan.php(14): Illuminate\Support\Facades\Artisan::add(Object(Books\AmazonOfferCommand))
#43 /home/laravel/vendor/laravel/framework/src/Illuminate/Console/Application.php(63): require('/home/laravel/...')
#44 /home/laravel/vendor/laravel/framework/src/Illuminate/Console/Application.php(33): Illuminate\Console\Application->boot()
#45 /home/laravel/artisan(45): Illuminate\Console\Application::start(Object(Illuminate\Foundation\Application))
#46 {main} [] []

Hidden dependency on Laravel > 4.1

Hello!

We have a Laravel 4.0.* project that was tracking dev-master. The project stopped working when the 1.3 release of Dispatcher came out. php artisan scheduled:run yielded the following error:

[Illuminate\Container\BindingResolutionException]
  Unresolvable dependency resolving [Parameter #0 [ <required> array $options ]].

This error happened on line 68 of Indatus\Dispatcher\Commands\Run.

The problem is that there was a bug in Laravel 4.0 where the IoC's build method did not properly resolve passed in dependencies. You can see that the passed in parameters are actually overwritten by a local variable. However, in 4.1, that same method looks like this. You can see that they fixed the overwrite.

The trouble is that the latest release of Dispatcher depends on the fix in 4.1 to work properly, yet the package does not indicate this dependency. So I figured I'd open up the issue to let you know.

Thanks!

When more than one scheduled, only first runs.

Hi,

Firstly, thanks for this amazing service.

When I have more than one scheduled command only the top one in the list runs. I can run them individually and if I shift the order in which they appear in the scheduled:summary list (app/start/artisan.php) then the top one is always the only one that runs.

Any ideas?

Cheers, James

ScheduledCommand not firing

I'm not receiving the e-mail I wanna send after successful job (I even thinks the whole thing isn't workin' what is inside the cron):

<?php

use Indatus\Dispatcher\Scheduling\ScheduledCommand;
use Indatus\Dispatcher\Scheduling\Schedulable;
use Indatus\Dispatcher\Drivers\Cron\Scheduler;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class Foobarommand extends ScheduledCommand {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'foo:bar';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "I'm not working";

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * When a command should run
     *
     * @param Scheduler $scheduler
     * @return \Indatus\Dispatcher\Scheduling\Schedulable
     */
    public function schedule(Schedulable $scheduler)
    {
        return $scheduler
            ->daily()
            ->hours([8,9,10,11,12,13,14,15,16,17,18,5])
            ->minutes(10);
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        return App::make('AdminController')->foobar();
    }

}


/// Admincoontroller:
public function foobar()
{
    $users = User::where('active',true)->get();
    echo "\nUsers: ".count($users);
    $i = 0;
    foreach($users as $db)
    {
        $xx = new \AcneMethod();

        $db = Job::whereId((int)$db->user_id)->first();
        $db->active   = true;
        $db->longitude  = $xx->thisworks;
        $db->save();
        $i++;
    }
    echo "\nOK\n";

    $input['description'] = $i;
    Mail::send('emails.cron', $input, function($message)
    {
        $message->to('[email protected]')->subject('Cron');
    });
}

// CRONTAB
# m h  dom mon dow   command
* * * * * /usr/bin/php /var/www/laravel/artisan scheduled:run 1>> /dev/null 2>&1

This works normally: return App::make('AdminController')->foobar();

HHVM support

At the moment it's not working, default php always worked. Manually calling the commands like hhvm artisan foo:bar is working.

Ability to schedule to run every other week

Would be nice to be able to set schedules to run every other week - like every other Wednesday.

I don't believe this is easy to do within cron which is one of the reasons I was looking for dispatcher or something similar. The solutions I found either required checks at the application level or custom bash time script in the cron job.

run command not fired with hhvm if I change the schedule

hey,

the issue is this, when I create a command and schedule it like this:

return $scheduler->hourly();

the output of the scheduled:run -d would be :

Running commands...
     test:get-albums: No schedules were due
     test:get-photos: No schedules were due

and the output of scheduled:run would be something like :

Segmentation fault (core dumped)

which i think is related to hhvm.

but if I change the schedule to run every minute like:

return $scheduler;

the output of the run command will be something like

test:get-albums: /usr/bin/hhvm /var/www/laravel/artisan test:get-albums > /dev/null &

which is nice and the command will be executed each and every minute

here is my setup info :

HipHop VM 3.3.0 (rel)
Compiler: tags/HHVM-3.3.0-0-g0a3cfb87b8a353fc7e1d15374f4adc413e37aba9
Repo schema: 9a391d9a03e15fccba1cde6d35c05b7cdd380238
Extension API: 20140829
Linux : Ubuntu 14.04

and am using ~1.4 in my composer.json file, any idea how can i solve this ?
thanks

Creating commands

Hi, just done a PR to change the publish config instead of views. But also wanted to add a link to this view on Laracasts on how to get started with custom commands https://laracasts.com/lessons/commands-101

I didn't know exactly where to put it, so instead I thought I would raise an issue for you guys to work it into the readme.

Laravel 5

A teammate of mine got this error and we assumed it was a Laravel 5 incompatibility.

'Illuminate\Foundation\Console\CommandMakeCommand' not found in /home/vagrant/Code/sst/vendor/indatus/dispatcher/src/Indatus/Dispatcher/Commands/Make.php on line 21

Is that true or just us not setting it up correctly? Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.