Coder Social home page Coder Social logo

crunz's Introduction

Repo no longer maintained, please use Crunz from new repo: https://github.com/crunzphp/crunz - more info here: #411

Crunz

Install a cron job once and for all, manage the rest from the code.

Crunz is a framework-agnostic package to schedule periodic tasks (cron jobs) in PHP using a fluent API.

Crunz is capable of executing any kind of executable command as well as PHP closures.

Version Packagist Packagist

Version Supported PHP versions
dev v3 (v3.2-dev) 7.4+
stable v3 (v3.1.0) 7.4+
stable v2 (v2.3.1) 7.2+
stable v1 (v1.12.4) 5.6-7.0+

Roadmap

Version Release date Active support until Bug support until Status
v1.x April 2016 April 2019 April 2020 End of life
v2.x April 2019 April 2021 April 2022 Bug support
v3.x April 2021 April 2023 April 2024 Active support

Installation

To install it:

composer require lavary/crunz

If the installation is successful, a command-line utility named crunz is symlinked to the vendor/bin directory of your project.

How It Works?

The idea is very simple: instead of installing cron jobs in a crontab file, we define them in one or several PHP files, by using the Crunz interface.

Here's a basic example:

<?php
// tasks/backupTasks.php

use Crunz\Schedule;

$schedule = new Schedule();
$task = $schedule->run('cp project project-bk');       
$task->daily();

return $schedule;

To run the tasks, you only need to install an ordinary cron job (a crontab entry) which runs every minute, and delegates the responsibility to Crunz' event runner:

* * * * * cd /project && vendor/bin/crunz schedule:run

The command schedule:run is responsible for collecting all the PHP task files and run the tasks which are due.

Task Files

Task files resemble crontab files. Just like crontab files they can contain one or more tasks.

Normally we create our task files in the tasks/ directory within the project's root directory.

By default, Crunz assumes all the task files reside in the tasks/ directory within the project's root directory.

There are two ways to specify the source directory: 1) Configuration file 2) As a parameter to the event runner command.

We can explicitly set the source path by passing it to the event runner as a parameter:

* * * * * cd /project && vendor/bin/crunz schedule:run /path/to/tasks/directory

Creating a Simple Task

In the terminal, change the directory to your project's root directory and run the following commands:

mkdir tasks && cd tasks
nano GeneralTasks.php

Then, add a task as below:

<?php
// tasks/FirstTasks.php

use Crunz\Schedule;

$schedule = new Schedule();

$task = $schedule->run('cp project project-bk'); 
$task
    ->daily()
    ->description('Create a backup of the project directory.');

// ...

// IMPORTANT: You must return the schedule object
return $schedule; 

There are some conventions for creating a task file, which you need to follow. First of all, the filename should end with Tasks.php unless we change this via the configuration settings.

In addition to that, we must return the instance of Schedule class at the end of each file, otherwise, all the tasks inside the file will be skipped by the event runner.

Since Crunz scans the tasks directory recursively, we can either put all the tasks in one file or across different files (or directories) based on their usage. This behavior helps us have a well organized tasks directory.

The Command

We can run any command or script by using run(). This method accepts two arguments: the command to be executed, and the command options (as an associative array) if there's any.

Normal Command or Script

<?php

use Crunz\Schedule;

$schedule = new Schedule();
$task = $schedule->run(PHP_BINARY . ' backup.php', ['--destination' => 'path/to/destination']);
$task
    ->everyMinute()
    ->description('Copying the project directory');

return $schedule;

In the above example, --destination is an option supported by backup.php script.

Closures

We can also write to a closure instead of a command:

<?php

use Crunz\Schedule;

$schedule = new Schedule();

$x = 12;
$task = $schedule->run(function() use ($x) { 
   // Do some cool stuff in here 
});

$task
    ->everyMinute()
    ->description('Copying the project directory');

return $schedule;

Frequency of Execution

There are a variety of ways to specify when and how often a task should run. We can combine these methods together to get our desired frequencies.

Units of Time

There are a group of methods which specify a unit of time (bigger than minute) as frequency. They usually end with ly suffix, as in hourly(), daily(), weekly, monthly(), quarterly(), and yearly .

All the events scheduled with this set of methods happen at the beginning of that time unit. For example weekly() will run the event on Sundays, and monthly() will run on the first day of each month.

The task below will run daily at midnight (start of the daily time period).

<?php
// ...
$task = $schedule->run(PHP_BINARY . ' backup.php');    
$task->daily();
// ...

Here's another one, which runs on the first day of each month.

<?php
// ...
$task = $schedule->run(PHP_BINARY . ' email.php');
$task->monthly();
// ...

Running Events at Certain Times

To schedule a one-off tasks, you may use on() method like this:

<?php
// ...
$task = $schedule->run(PHP_BINARY . ' email.php'); 
$task->on('13:30 2016-03-01');
// ...

The above task will run on the first of march 2016 at 01:30 pm.

On() accepts any date format parsed by PHP's strtotime function.

To specify the time of a task we use at() method:

<?php
// ...
$task = $schedule->run(PHP_BINARY . ' email.php'); 
$task
    ->daily()
    ->at('13:30');
// ...

If we only pass a time to the on() method, it will have the same effect as using at()

<?php
// ...
$task = $schedule->run(PHP_BINARY . ' email.php');   
$task
    ->daily()
    ->on('13:30');
         
// is the sames as
$task = $schedule->run(PHP_BINARY . ' email.php');       
$task
    ->daily()
    ->at('13:30');
// ...

We can combine the "Unit of Time" methods eg. daily(), monthly() with the at() or on() constraint in a single statement if we wish.

The following task will be run every hour at the 15th minute

<?php
// ...
$task = $schedule->run(PHP_BINARY . ' feedmecookie.php'); 
$task
    ->hourlyAt('15');
// ...

hourlyOn('15') could have been used instead of hourlyAt('15') with the same result

The following task will be run Monday at 13:30

<?php
// ...
$task = $schedule->run(PHP_BINARY . ' startofwork.php'); 
$task
    ->weeklyOn(1,'13:30');
// ...

Sunday is considered day 0 of the week.

If we wished for the task to run on Tuesday (day 2 of the week) at 09:00 we would have used:

<?php
// ...
$task = $schedule->run(PHP_BINARY . ' startofwork.php'); 
$task
    ->weeklyOn(2,'09:00');
// ...

Task Life Time

In a crontab entry, we can not easily specify a task's lifetime (the period of time when the task is active). However, it's been made easy in Crunz:

<?php
//
$task = $schedule->run(PHP_BINARY . ' email.php');
$task
    ->everyFiveMinutes()
    ->from('12:30 2016-03-04')
    ->to('04:55 2016-03-10');
 //       

Or alternatively we can use the between() method to accomplish the same result:

<?php
//
$task = $schedule->run(PHP_BINARY . ' email.php');
$task
    ->everyFiveMinutes()
    ->between('12:30 2016-03-04', '04:55 2016-03-10');

 //       

If we don't specify the date portion, the task will be active every day but only within the specified duration:

<?php
//
$task = $schedule->run(PHP_BINARY . ' email.php');
$task
     ->everyFiveMinutes()
     ->between('12:30', '04:55');

 //       

The above task runs every five minutes between 12:30 pm and 4:55 pm every day.

An example of restricting a task from running only during a certain range of minutes each hour can be achieved as follows:

<?php
//

$hour = date('H');
$startminute = $hour.':05';
$endminute = $hour.':15';

$task = $schedule->run(PHP_BINARY . ' email.php');
$task
     ->hourly()
     ->between($startminute, $endminute);

 //       

The above task runs every hour between minutes 5 to 15

Weekdays

Crunz also provides a set of methods which specify a certain day in the week.

  • mondays()
  • tuesdays()
  • ...
  • sundays()
  • weekedays()
  • weekends()

These methods have been designed to be used as a constraint and should not be used alone. The reason is that weekday methods just modify the Day of Week field of a cron job expression.

Consider the following example:

<?php
// Cron equivalent:  * * * * 1
$task = $schedule->run(PHP_BINARY . ' startofwork.php');
$task->mondays();

At first glance, the task seems to run every Monday, but since it only modifies the "day of week" field of the cron job expression, the task runs every minute on Mondays.

This is the correct way of using weekday methods:

<?php
// ...
$task = $schedule->run(PHP_BINARY . ' startofwork.php');
$task    
    ->mondays()
    ->at('13:30');

// ...

(An easier to read alternative with a similar result ->weeklyOn(0,'13:30') to that shown in a previously example above)

The Classic Way

We can also do the scheduling the old way, just like we do in a crontab file:

<?php

$task = $schedule->run(PHP_BINARY . ' email.php');
$task->cron('30 12 * 5-6,9 Mon,Fri');

Setting Individual Fields

Crunz's methods are not limited to the ready-made methods explained. We can also set individual fields to compose custom frequencies similar to how a classic crontab would composed them. These methods either accept an array of values, or list arguments separated by commas:

<?php
// ...
$task = $schedule->run(PHP_BINARY . ' email.php');
$task       
    ->minute(['1-30', 45, 55])
    ->hour('1-5', 7, 8)
    ->dayOfMonth(12, 15)
    ->month(1);

Or:

<?php
// ...
$task = $schedule->run(PHP_BINARY . ' email.php');
$task
    ->minute('30')
    ->hour('13')
    ->month([1,2])
    ->dayofWeek('Mon', 'Fri', 'Sat');

// ...

Based on our use cases, we can choose and combine the proper set of methods, which are easier to use.

Running Conditions

Another thing that we cannot do very easily in a traditional crontab file is to make conditions for running the tasks. This has been made easy by when() and skip() methods.

Consider the following code:

<?php
//
$task = $schedule->run(PHP_BINARY . ' email.php');
$task
    ->everyFiveMinutes()
    ->between('12:30 2016-03-04', '04:55 2016-03-10')
    ->when(function() {
        if ((bool) (time() % 2)) {
            return true;
        }
        
        return false;
    });

Method when() accepts a callback, which must return TRUE for the task to run. This is really useful when we need to check our resources before performing a resource-hungry task.

We can also skip a task under certain conditions, by using skip() method. If the passed callback returns TRUE, the task will be skipped.

<?php
//
$task = $schedule->run(PHP_BINARY . ' email.php');
$task
    ->everyFiveMinutes()
    ->between('12:30 2016-03-04', '04:55 2016-03-10')
    ->skip(function() {
        if ((bool) (time() % 2)) {
            return true;
        }
        
        return false;  
    });

 //       

We can use these methods several times for a single task. They are evaluated sequentially.

Changing Directories

You can use the in() method to change directory before running a command:

<?php

// ...

$task = $schedule->run('./deploy.sh');
$task
    ->in('/home')
    ->weekly()
    ->sundays()
    ->at('12:30')
    ->appendOutputTo('/var/log/backup.log');

// ...

return $schedule;

Parallelism and the Locking Mechanism

Crunz runs the scheduled events in parallel (in separate processes), so all the events which have the same frequency of execution, will run at the same time asynchronously. To achieve this, Crunz utilizes the symfony/Process library for running the tasks in sub-processes.

If the execution of a task lasts until the next interval or even beyond that, we say that the same instances of a task are overlapping. In some cases, this is a not a problem. But there are times, when these tasks are modifying database data or files, which might cause unexpected behaviors, or even data loss.

To prevent critical tasks from overlapping each other, Crunz provides a locking mechanism through preventOverlapping() method, which, ensures no task runs if the previous instance is already running.

<?php
//
$task = $schedule->run(PHP_BINARY . ' email.php');
$task
    ->everyFiveMinutes()
    ->preventOverlapping();
 //       

By default, crunz uses file based locking (if no parameters are passed to preventOverlapping). For alternative lock mechanisms, crunz uses the symfony/lock component that provides lock mechanisms with various stores. To use this component, you can pass a store to the preventOverlapping() method. In the following example, the file based FlockStore is used to provide an alternative lock file path.

<?php

use Symfony\Component\Lock\Store\FlockStore;

$store = new FlockStore(__DIR__ . '/locks');
$task = $schedule->run(PHP_BINARY . ' email.php');
$task
    ->everyFiveMinutes()
    ->preventOverlapping($store);

As of Symfony 5.0 the StoreInterface has been split into BlockingStoreInterface and PersistingStoreInterface. To use any of the persistent locks (Redis, PDO, etc) they need to be decorated by the RetryTillSaveStore.

<?php

use Symfony\Component\Lock\Store\RedisStore;
use Symfony\Component\Lock\Store\RetryTillSaveStore;

$redis = new Redis();
$redis->connect('localhost');
$persistingStore = new RedisStore($redis);
$blockingStore = new RetryTillSaveStore($persistingStore);

$task = $schedule->run(PHP_BINARY . ' email.php');
$task
    ->everyFiveMinutes()
    ->preventOverlapping($blockingStore);

Keeping the Output

Cron jobs usually have outputs, which is normally emailed to the owner of the crontab file, or the user(s) set by the MAILTO environment variable inside the crontab file.

We can also redirect the standard output to a physical file using > or >> operators:

* * * * * /command/to/run >> /var/log/crons/cron.log

This kind of output logging has been automated in Crunz. To automatically send each event's output to a log file, we can set log_output and output_log_file options in the configuration file accordingly:

# Configuration settings

## ...
log_output:      true
output_log_file: /var/log/crunz.log
## ...

This will send the events' output (if executed successfully) to /var/log/crunz.log file. However, we need to make sure we are permitted to write to the respective file.

If we need to log the outputs on an event-basis, we can use appendOutputTo() or sendOutputTo() methods like this:

<?php
//
$task = $schedule->run(PHP_BINARY . ' email.php');
$task
    ->everyFiveMinutes()
    ->appendOutputTo('/var/log/crunz/emails.log');

 //       

Method appendOutputTo() appends the output to the specified file. To override the log file with new data after each run, we use saveOutputTo() method.

It is also possible to send the errors as emails to a group of recipients by setting email_output and mailer settings in the configuration file.

Error Handling

Crunz makes error handling easy by logging and also allowing you add a set of callbacks in case of an error.

Error Callbacks

You can set as many callbacks as needed to run in case of an error:

<?php

use Crunz\Schedule;

$schedule = new Schedule();

$task = $schedule->run('command/to/run');
$task->everyFiveMinutes();

$schedule
->onError(function() {
   // Send mail
})
->onError(function() {
   // Do something else
});

return $schedule;

If there's an error the two defined callbacks will be executed.

Error Logging

To log the possible errors during each run, we can set log_error and error_log_file settings in the configuration file as below:

# Configuration settings

# ...
log_errors:      true
errors_log_file: /var/log/error.log
# ...

As a result, if the execution of an event is unsuccessful for some reasons, the error message is appended to the specified error log file. Each entry provides useful information including the time it happened, the event description, the executed command which caused the error, and the error message itself.

It is also possible to send the errors as emails to a group of recipients by setting email_error and mailer settings in the configuration file.

Custom logger

To use your own logger create class implementing \Crunz\Application\Service\LoggerFactoryInterface, for example:

<?php

namespace Vendor\Package;

use Crunz\Application\Service\ConfigurationInterface;
use Crunz\Application\Service\LoggerFactoryInterface;
use Psr\Log\AbstractLogger;
use Psr\Log\LoggerInterface;

final class MyEchoLoggerFactory implements LoggerFactoryInterface
{
    public function create(ConfigurationInterface $configuration): LoggerInterface
    {
        return new class extends AbstractLogger {
            /** @inheritDoc */
            public function log(
                $level,
                $message,
                array $context = array()
            ) {
                echo "crunz.{$level}: {$message}";   
            }
        };
    }
}

then use this class name in config:

# ./crunz.yml file
 
logger_factory: 'Vendor\Package\MyEchoLoggerFactory'

Done.

Pre-Process and Post-Process Hooks

There are times when we want to do some kind of operations before and after an event. This is possible by attaching pre-process and post-process callbacks to the respective event.

To do this, we use before() and after() on both Event and Schedule objects, meaning we can have pre and post hooks on an event-basis as well as schedule basis. The hooks bind to schedule will run before all events, and after all the events are finished.

<?php

use Crunz\Schedule;

$schedule = new Schedule();

$task = $schedule->run(PHP_BINARY . ' email.php');
$task
    ->everyFiveMinutes()
    ->before(function() { 
        // Do something before the task runs
    })
    ->before(function() { 
        // Do something else
    })
    ->after(function() {
        // After the task is run
    });
 
$schedule
    ->before(function () {
       // Do something before all events
    })
    ->after(function () {
       // Do something after all events are finished
    })
    ->before(function () {
       // Do something before all events
    });

We might need to use these methods as many times we need by chaining them.

Post-execution callbacks are only called if the execution of the event has been successful.

Other Useful Commands

We've already used a few of crunz commands like schedule:run and publish:config.

To see all the valid options and arguments of crunz, we can run the following command:

vendor/bin/crunz --help

Listing Tasks

One of these commands is crunz schedule:list, which lists the defined tasks (in collected *.Tasks.php files) in a tabular format.

vendor/bin/crunz schedule:list

+---+---------------+-------------+--------------------+
| # | Task          | Expression  | Command to Run     |
+---+---------------+-------------+--------------------+
| 1 | Sample Task   | * * * * 1 * | command/to/execute |
+---+---------------+-------------+--------------------+

Force run

While in development it may be useful to force run all tasks regardless of their actual run time, which can be achieved by adding --force to schedule:run:

vendor/bin/crunz schedule:run --force

To force run a single task, use the schedule:list command above to determine the Task number and run as follows:

vendor/bin/crunz schedule:run --task 1 --force

Generating Tasks

There is also a useful command named make:task, which generates a task file skeleton with all the defaults, so we won't have to write them from scratch. We can modify the output file later based on our requirements.

For example, to create a task, which runs /var/www/script.php every hour on Mondays, we run the following command:

vendor/bin/crunz make:task exampleOne --run scripts.php --in /var/www --frequency everyHour --constraint mondays
Where do you want to save the file? (Press enter for the current directory)

When we run this command, Crunz will ask about the location we want to save the file. By default, it is our source tasks directory.

As a result, the event is defined in a file named exampleOneTasks.php within the specified tasks directory.

To see if the event has been created successfully, we list the events:

crunz schedule:list

+---+------------------+-------------+----------------+
| # | Task             | Expression  | Command to Run |
+---+------------------+-------------+----------------+
| 1 | Task description | 0 * * * 1 * | scripts.php    |
+---+------------------+-------------+----------------+

To see all the options of make:task command with all the defaults, we run this:

vendor/bin/crunz make:task --help

Debugging tasks

To show basic information about task run:

vendor/bin/crunz task:debug 1

Above command should output something like this:

+----------------------+-----------------------------------+
| Debug information for task '1'                           |
+----------------------+-----------------------------------+
| Command to run       | php -v                            |
| Description          | Inner task                        |
| Prevent overlapping  | No                                |
+----------------------+-----------------------------------+
| Cron expression      | * * * * *                         |
| Comparisons timezone | Europe/Warsaw (from config)       |
+----------------------+-----------------------------------+
| Example run dates                                        |
| #1                   | 2020-03-08 09:27:00 Europe/Warsaw |
| #2                   | 2020-03-08 09:28:00 Europe/Warsaw |
| #3                   | 2020-03-08 09:29:00 Europe/Warsaw |
| #4                   | 2020-03-08 09:30:00 Europe/Warsaw |
| #5                   | 2020-03-08 09:31:00 Europe/Warsaw |
+----------------------+-----------------------------------+

Configuration

There are a few configuration options provided by Crunz in YAML format. To modify the configuration settings, it is highly recommended to have your own copy of the configuration file, instead of modifying the original one.

To create a copy of the configuration file, first we need to publish the configuration file:

/project/vendor/bin/crunz publish:config
The configuration file was generated successfully

As a result, a copy of the configuration file will be created within our project's root directory.

The configuration file looks like this:

# Crunz Configuration Settings

# This option defines where the task files and
# directories reside.
# The path is relative to the project's root directory,
# where the Crunz is installed (Trailing slashes will be ignored).
source: tasks

# The suffix is meant to target the task files inside the ":source" directory.
# Please note if you change this value, you need
# to make sure all the existing tasks files are renamed accordingly.
suffix: Tasks.php

# Timezone is used to calculate task run time
# This option is very important and not setting it is deprecated
# and will result in exception in 2.0 version.
timezone: ~

# This option define which timezone should be used for log files
# If false, system default timezone will be used
# If true, the timezone in config file that is used to calculate task run time will be used
timezone_log: false

# By default the errors are not logged by Crunz
# You may set the value to true for logging the errors
log_errors: false

# This is the absolute path to the errors' log file
# You need to make sure you have the required permission to write to this file though.
errors_log_file:

# By default the output is not logged as they are redirected to the
# null output.
# Set this to true if you want to keep the outputs
log_output: false

# This is the absolute path to the global output log file
# The events which have dedicated log files (defined with them), won't be
# logged to this file though.
output_log_file:

# By default line breaks in logs aren't allowed.
# Set the value to true to allow them.
log_allow_line_breaks: false

# By default empty context arrays are shown in the log.
# Set the value to true to remove them.
log_ignore_empty_context: false

# This option determines whether the output should be emailed or not.
email_output: false

# This option determines whether the error messages should be emailed or not.
email_errors: false

# Global Swift Mailer settings
#
mailer:
    # Possible values: smtp, mail, and sendmail
    transport: smtp
    recipients:
    sender_name:
    sender_email:


# SMTP settings
#
smtp:
    host:
    port:
    username:
    password:
    encryption:

As you can see there are a few options like source which is used to specify the source tasks directory. The other options are used for error/output logging/emailing purposes.

Each time we run Crunz commands, it will look into the project's root directory to see if there's any user-modified configuration file. If the configuration file doesn't exists, it will use the one shipped with the package.

Development ENV flags

The following environment flags should be used only while in development. Typical end-users do not need to, and should not, change them.

CRUNZ_CONTAINER_DEBUG

Flag used to enable/disable container debug mode, useful only for development. Enabled by default in docker-compose.

CRUNZ_DEPRECATION_HANDLER

Flag used to enable/disable Crunz deprecation handler, useful only for integration tests. Disabled by default for tests.

Contributing

Which branch should I choose?

In most cases you should target branch 1.12.x, as this is active development branch. Branch master is for future release, but all bugs/features should go to 1.11.x anyway.

If You Need Help

Please submit all issues and questions using GitHub issues and I will try to help you.

Credits

License

Crunz is free software distributed under the terms of the MIT license.

crunz's People

Contributors

andrewmy avatar arthurbarros avatar aviduda avatar codermarcel avatar davidsneighbour avatar digilist avatar drjayvee avatar ecofishrcr avatar erfan723 avatar falldi avatar hashnz avatar iluuu1994 avatar jhoughtelin avatar lavary avatar m-hume avatar mareksuscak avatar marklittlewood avatar mindcreations avatar pablokowalczyk avatar philetaylor avatar radarhere avatar sadeghpm avatar simmonspaul avatar timurbakarov avatar vinkla 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

crunz's Issues

Custom files finder / initialization strategy

Hi there!

Thanks for this awesome library!

I want to use Crunz in CMF with multiple directories for scheduled events files (app, core and some modules). These directories are detected dynamically and can not be set via cli argument or yml config. As I understood doc and the code correctly, it's not possible to configure Crunz to use custom files finder. So my suggestion is to implement special class which would handle files detecting/loading and use it instead of collectTaskFiles method (and it's clones in other files). But I don't see any way to inject this file into crunz console app (maybe create namespace for these loaders, set loader codename in config and search loader class in namespace by specified codename). I may make PR for this but I want to hear your opinion for this issue first.

Why is the dependency on monolog so restrictive?

You depend on the exact version 1.19.0 of monolog/monolog, instead of something like ^1.19
Is there any reason for that? It makes it impossible to get a newer version of the package while dependening on lavary/crunz.

Specify the config file in the command line

Hi,
Here is the situation, usually we have several different environment(such as production/local development), that means the config is different to each env(such as log file location and some settings).

Just had a quick looking up in the source code and found out that, I can specify ENV parameter - CRUNZ_BASE_DIR, which will be checked when loading the configuration file(crunz.yml).

But, CRUNZ_BASE_DIR has to be set in the php code, which is not handy, as I have to write another initializing file which only set CRUNZ_BASE_DIR based on the env and inject it to the crunz running context. For now, the only way is modify the source code, or I have to write a "wrapper" launcher.

So, is it possible to support something like this:
path/to/vendor/bin/crunz schedule:run --conf path/to/crunz.yml

Let me know if I missed something.
Thanks!

New package maintainer

Hello. It looks like this package got abandoned and there is nobody looking into issues and pull requests.

@lavary would mind giving another person write access to this repository if somebody is willing to take responsibility for this repository?

Closure on Windows - not recognized command

I'm getting an error when trying to test my first task from the Windows command line. I'm still working on getting my head wrapped around Crunz, so this may very well be a silly mistake on my part.

Here's my task code.

use Crunz\Schedule;

$schedule = new Schedule();

$schedule->run( function() {
                echo 'Howdy'; 
        } )
        ->description( 'Test task' )
        ->everyMinute();

return $schedule;

The error I'm getting is

crunz.ERROR: 'c:\path\to\vendor\lavary\crunz\src/../crunz' is not recognized as an internal or external commad, operable program or batch file

It only does this when I'm trying to use a closure. If I enter a command like dir it works perfectly.

schedule:list works and shows object(Closure) as the task to run.

I've tried running the crunz.bat file from the folder it's in and also from the project root with the path in front. I've also tried running php crunz schedule:run from within the lavary/crunz folder, and that didn't work either.

appendOutputTo

I nice to have would be to include the current timestamp when adding Log Output to a file.

delete,pause task from scheduler list by id

Hi guys,

do we have the ability to delte or pause a specific task by id throught command?

e.g.
crunz tasks remove 1
crunz tasks pause 2
crunz tasks resume 1

at the moment, we can't delete the task from the list, can we?

preventOverlapping is not work

preventOverlapping is not work since commit cabc7a0 (Create an event runner with closure call support )

Event::lock() newer called and have incorrect code: undefined variable $event

Supported for PHP 5.3

Hi,

I really like your library, it is super useful. I just wonder what is the reason for this library to require PHP 5.5? We have quite old server software and we can't upgrade to newer PHP version at the moment (only has PHP5.3). Thank you.

No task is due

I have the following task
$schedule->run('/var/www/xxxx/bin/console.php cron:import-listings') ->cron('59 * * * *') ->appendOutputTo('/var/log/xxxx.log') ->preventOverlapping();
I keep changing the minute to see if it works but I only see No task is due when time matches the cron value. Am I missing something?

posix_getsid error

Exit with exception 'ErrorException' with message 'posix_getsid() expects parameter 1 to be long, string given' in vendor/lavary/crunz/src/Event.php:250

SMTP setup does not work correctly

Hi
I ran the code using ssh in my server.
/usr/local/bin/php /home/souvenir/public_html/new/cron2/vendor/lavary/crunz/crunz schedule:run

But i got error saying "Invalid type for path "crunz.smtp". Expected array, but got strings"
My smtp set up is

smtp:
    host:mail.domain.com 
    port:465
    username:*****
    password:admin1234
    encryption:SSL/TLS 

Is there anyone who faced this issue?
Thank you

Enumeration of tasks

Whenever I run crunz schedule:list the list that is generated marks all entries with the # 1, example below:

$ ./crunz schedule:list
+---+----------------------------------+----------------+------------------------------+
| # | Task | Expression | Command to Run |
+---+----------------------------------+----------------+------------------------------+
| 1 | Garbage Collect Expired Sessions | 0 * * * * * | ./console cron sessions -q |
| 1 | Collect Stats from Previous Day | 30 0 * * * * | ./console stats:collect -q |
| 1 | General Garbage Collector | 45 1 * * 7 * | ./console cron garbage -q |
| 1 | Process Events | * * * * * * | ./console cron events -q |
| 1 | Reminders Level 1 | 50 11 * * * * | ./console cron reminders1 -q |
| 1 | Reminders Level 2 | 40 11 * * * * | ./console cron reminders2 -q |
| 1 | Reminders Level 3 | 30 11 * * * * | ./console cron reminders3 -q |
| 1 | Scheduled Promotions | */15 * * * * * | ./console cron promote -q |
| 1 | Shuffle and Stay on Top Control | 0 */2 * * * * | ./console cron shuffle -q |
+---+----------------------------------+----------------+------------------------------+

I would expect the "number" column to be incremented by one for each row.

Similar package. Collaborate?

Aloha! I created a similar package for my company (which we use in production hundreds of times a day), and recently posted it to github. I had intended to expand and clean it up.

We seem to be trying to solve a lot of the same problems, and each have features the other package doesn't. Would it be worth looking through my library and collaborating? I'd be happy to merge my work over to your library where appropriate.

My package is at https://github.com/chrismichaels84/mistletoe. It is fully PSR compliant, well tested, and build on SOLID principles.

Some features include:

  • Simplify ALL cronjobs into a single job
  • Environment detection and limiting (only run certain tasks in production)
  • Tasks may be console commands, classes, or callables
  • Fluent cron schedule builder
  • An included TaskRunner
  • Easy to create custom task runners
  • A working phar

Some things it may have to offer are:

  • Transforming cron expressions into natural language expressions
  • Creating TaskRunners
  • Run tasks in sequence (one followed by two followed by three)
  • Environment detection so you can run some on production and other on development

Just a thought.

Unable to install

Hi,

I am trying to install the using composer - composer.phar require lavary/crunz

I am getting the following error:

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Can only install one of: lavary/crunz[v1.4.8, dev-master].
- Can only install one of: lavary/crunz[v1.4.8, dev-master].
- Installation request for lavary/crunz ^1.4.8 -> satisfiable by lavary/crunz[v1.4.8].
- Installation request for lavary/crunz dev-master -> satisfiable by lavary/crunz[dev-master].

Any idea what can be the fix?

Thanks!

Doesn't seem to detect the directory root

I've started to play with this project, and the first stopper that I find is that it doesn't seem to properly detect the project root.

When I run any CLI command, it thinks the project root is inside vendor/lavary. That makes, for example the command make:task to create the file in vendor/lavary/tasks/fooTask.php, instead of tasks/fooTask.php
The same happens with the crunz.yaml config file. If I set something in the copy inside the project root, it doesn't take effect. However, it does If I change the file vendor/lavary/crunz.yml (which I think it has been created after running the publish:config command)

I'm running the commands from the project root, with vendor/bin/crunz make:task, but it seems to do the same if you change current dir to vendor/bin and run crunz make:task.

Also, the all commands throw lots of warnings until you create the crunz.yml file, because it is not able to open it.

PHP Warning:  file_get_contents(/home/user/crunz_test/vendor/lavary/crunz/src/Configuration/../crunz.yml): failed to open stream: No such file or directory in /home/user/crunz_test/vendor/lavary/crunz/src/Configuration/Configuration.php on line 62

Undefined index: year in vendor/lavary/crunz/src/Event.php on line 370

This error occurs when using on method in 'Running Events at Certain Times'

    /**
     * Position of cron fields
     *
     * @var array
     */
    protected $fieldsPosition = [
        'minute' => 1,
        'hour'   => 2,
        'day'    => 3,
        'month'  => 4,
        'week'   => 5,
    ];

    /**
     * Schedule the event to run on a certain date
     *
     * @param  string  $date
     *
     * @return $this
     */
    public function on($date)
    {
        
        $date     = date_parse($date);
        $segments = array_only($date, array_flip($this->fieldsPosition));

        if ($date['year']) {
 
            $this->skip(function () use ($segments) {
                return (int) date('Y') != $segments['year'];
            });

        }
                
        foreach ($segments as $key => $value) {   
            if ($value != false) {                
                $this->spliceIntoPosition($this->fieldsPosition[$key], (int) $value);
            }
        }

        return $this;          
    }

Apparently missing the position for the year in the attribute 'fieldsPosition'.

Integration with existing Symfony Console

Hi!

I have an existing application using symfony/console.

Will crunz works if I add all commands defined in Console/CommandKernel in my own console declaration? I think it'll works but I prefer to ask before digging the doc :)

Always getting "No event is due! "

After running vendor/bin/crunz schedule:list

I have the following, but the cron log is always saying: No event is due!

+-----+---------------------------------------+-----------------+----------------------------------------------------------------------+
| # | Task | Expression | Command to Run |
+-----+---------------------------------------+-----------------+----------------------------------------------------------------------+
| 1 | XXXXXX | 30 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 8190 |
| 2 | XXXXXX | 30 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 8678 |
| 3 | XXXXXX | * 23 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 237 |
| 4 | XXXXXX | 30 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 3758 |
| 5 | XXXXXX | 30 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 7024 |
| 6 | XXXXXX | 30 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 8186 |
| 7 | XXXXXX | 30 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 8686 |
| 8 | XXXXXX | 30 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 9146 |
| 9 | XXXXXX | * 2 16 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 9305 |
| 10 | XXXXXX | 30 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 8191 |
| 11 | XXXXXX | * 5 16 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 3272 |
| 12 | XXXXXX | * 23 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 3901 |
| 13 | XXXXXX | * 23 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 243 |
| 14 | XXXXXX | * 21 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 6966 |
| 15 | XXXXXX | * 23 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 5278 |
| 16 | XXXXXX | * 12 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 9059 |
| 17 | XXXXXX | * 4 16 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 3259 |
| 18 | XXXXXX | * 20 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 5106 |
| 19 | XXXXXX | 30 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 8179 |
| 20 | XXXXXX | 30 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 8687 |
| 21 | XXXXXX | * 14 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run1 3371 |
| 22 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 12.90_77.60 |
| 23 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 18.95_72.80 |
| 24 | YYYYYYY | 30 22 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 35.10_-117.90 |
| 25 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 13.05_77.60 |
| 26 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 28.65_77.20 |
| 27 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 25.20_75.85 |
| 28 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 13.10_77.55 |
| 29 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 20.00_77.00 |
| 30 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 10.00_76.40 |
| 31 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 12.95_77.55 |
| 32 | YYYYYYY | 30 1 16 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 -36.90_174.80 |
| 33 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 12.90_77.55 |
| 34 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 10.00_76.30 |
| 35 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 13.00_77.55 |
| 36 | YYYYYYY | 30 4 16 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 -27.40_153.05 |
| 37 | YYYYYYY | 30 22 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 37.35_-122.10 |
| 38 | YYYYYYY | 30 22 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 37.40_-122.10 |
| 39 | YYYYYYY | 30 22 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 34.10_-118.30 |
| 40 | YYYYYYY | 30 20 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 17.20_-88.90 |
| 41 | YYYYYYY | 30 20 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 17.25_-88.70 |
| 42 | YYYYYYY | 30 22 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 36.20_-115.10 |
| 43 | YYYYYYY | 30 11 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 0.40_33.20 |
| 44 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 10.00_76.35 |
| 45 | YYYYYYY | 30 3 16 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 -33.90_150.75 |
| 46 | YYYYYYY | 30 19 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 40.70_-74.00 |
| 47 | YYYYYYY | 30 1 16 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 -36.70_174.80 |
| 48 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 28.70_77.20 |
| 49 | YYYYYYY | * 9 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 12.30_76.55 |
| 50 | YYYYYYY | 30 13 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run2 47.50_19.00 |
| 51 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 12.90_77.60 |
| 52 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 18.95_72.80 |
| 53 | ZZZZZZ | * 22 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 35.10_-117.90 |
| 54 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 13.05_77.60 |
| 55 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 28.65_77.20 |
| 56 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 25.20_75.85 |
| 57 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 13.10_77.55 |
| 58 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 20.00_77.00 |
| 59 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 10.00_76.40 |
| 60 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 12.95_77.55 |
| 61 | ZZZZZZ | * 1 16 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 -36.90_174.80 |
| 62 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 12.90_77.55 |
| 63 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 10.00_76.30 |
| 64 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 13.00_77.55 |
| 65 | ZZZZZZ | * 4 16 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 -27.40_153.05 |
| 66 | ZZZZZZ | * 22 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 37.35_-122.10 |
| 67 | ZZZZZZ | * 22 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 37.40_-122.10 |
| 68 | ZZZZZZ | * 22 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 34.10_-118.30 |
| 69 | ZZZZZZ | * 20 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 17.20_-88.90 |
| 70 | ZZZZZZ | * 20 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 17.25_-88.70 |
| 71 | ZZZZZZ | * 22 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 36.20_-115.10 |
| 72 | ZZZZZZ | * 11 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 0.40_33.20 |
| 73 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 10.00_76.35 |
| 74 | ZZZZZZ | * 3 16 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 -33.90_150.75 |
| 75 | ZZZZZZ | * 19 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 40.70_-74.00 |
| 76 | ZZZZZZ | * 1 16 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 -36.70_174.80 |
| 77 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 28.70_77.20 |
| 78 | ZZZZZZ | 30 8 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 12.30_76.55 |
| 79 | ZZZZZZ | * 13 15 11 * * | /usr/bin/php /home/sample/jobs/runner.php run3 47.50_19.00 |
+-----+---------------------------------------+-----------------+----------------------------------------------------------------------+

I used a test task to run every minute, every 2 minutes and so on, they seem to be working but all these crons are not working, getting same value as "No event is due! "

Using function output?

I have implemented Crunz. I've created an Event with a Closure that initially used Doctrine's EntityManager to remove some sort of entity that was older than 24hours. That did not seem to work because the events where serialised by some library called SuperSerialise. Anything Doctrine related and serialisation do not play well.

I've moved the Closure to a separate function in the same Task file. The system is able to successfully execute the command, but the output is this;

[user@some-server:~/some-directory$ /usr/local/php7/bin/php vendor/bin/crunz schedule:run
sh: 1: Removed: not found

The function will output the amount of entries removed, see this example:

function executeCronjob($parameters)
{
    try {
        // php-code here    

        return 'Removed ' . $tokenCount . ' tokens';
    } catch (\Exception $exception) {
        return $exception->getMessage();
    }
}

Should I use return or echo for the output of the function?

Edit; nvm using echo resolved my issue.

Job stats and management

Hello,
just a feature request:
do you mind to add the following stats functions:

  1. what job will be run next
  2. what jobs have been running now
  3. what job has finished last
  4. detect the job error level (bool error/success or unix int 0=success or >0=error code)
  5. job naming to ease the management

Schedule closure function outputs empty crunz.ERROR

use Crunz\Schedule;

$schedule = new Schedule();
$schedule->run(function()  {
         });

return $schedule;

When I run a schedule command that's a closure function, I get

crunz.ERROR: [] []

outputted to my error log.

Not a big issue, but annoying to fill up my crunz error log with this? Any idea what's happening?

Change config from code

I want to have my default values for some of the fields like email information, but I want my users to be able to modify some of the config.

Can I have only one default config, and then have the other config to modify?

Problem with ->in(dirname) on Windows

In the buildCommand function of Events.php, the change directory instruction is concatenated to rest of the command using a semi colon. This does not work under Windows. Commands can be joined with an ampersand.

A possible fix is to replace

$command .= 'cd ' . $this->cwd . ' & ';

with
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
## Windows
$command .= 'cd ' . $this->cwd . ' & ';
} else {
## Not Windows
$command .= 'cd ' . $this->cwd . '; ';
}

Problems with Freebsd

Hi.
On a server running FreeBSD I got an error "Ambiguous output redirect."
Because structure "2>&1" is not working with shell csh
I propose to to make check OS in Event class, method buildCommand and fix command.

$command  = $this->command . $redirect . $this->output;
$command .= (stristr(strtolower(PHP_OS), 'bsd')) ? ' &' : ' 2>&1 &';

Debugging

In the current setup debugging is hard as there is no way to test discrete cronjobs for if they perform well without sending them to the crontab.

Would be nice to have the following additional options for the command schedule:run

  • Task --> to indicate which task number from schedule:list is to be run now
  • Force --> force run the task immediately and don't match a specific timespot

would make implementing && testing much more fun

Symfony Version >= 2.7 and < 3.0 support

Currently i have symfony project with symfony version 2.8.x - when trying to install crunz, it rejected because some of the dependecies is for Symfony >= 3.0 like symfony/yaml, symfony/finder, and symfony/process. Is there any plan for downgrade the lib versions, so it can be use for symfony < 3.0 ?

Crunz sends output email even if the output is empty

Hi,

I was using traditional cronjobs with a MAILTO variable and some other args to receive mails only when my scripts output something (i.e. not empty).

I switched to crunz and tried to reproduce the same thing. Unfortunately, I can't. I receive emails for every cronjob even if the output of the scripts is empty. I think crunz should only send an output (when we activate them in the conf file) if there is something to send. If it's empty, nothing should be mailed.

Am I missing something?

Regards

High CPU usage

I used crunz with a php script of sending email ("yiic emailSpool loop" http://cornernote.github.io/yii-email-module). In this script, it'll fetch spooled email (e.g 10 emails) from db and send them, then sleep 1 second, then next 10 emails,...

The problem is the schedule:run used very high CPU load

Pls look at process 84672

screen shot 2017-07-26 at 3 29 11 pm
screen shot 2017-07-26 at 3 30 04 pm

I did try to run yiic emailSpool loop without crunz
#yiic emailSpool loop &
and it only takes 0.1% cpu (the same result if i put this script to crontab -e)
Actually there isn't many emails to send, most of the time this script hit db get 0 spooled emails, sleep, hit db, 0 emails, sleep, ... but the server is always around 90-100% CPU load

Using another root directory for everything

What is the best way to use another root directory for crunz? I rather not have my task nor configuration file in the composer/ directory.

I know it is possible for the schedule:run and schedule:list
We can explicitly set the source path by passing it to the event runner as a parameter

But this applies only to finding the tasks? It still seems to require config file in composer/.
An optional --rootdirectory option to "crunz" would be great.

Task next execution time?

Hi,
I was wondering if there's a way to get the next execution time for a Task.
Thanks in advance,

Alejandro

Neither appendOutputTo() or sendOutputTo() works

Here is my code:

use Crunz\Schedule;
$schedule = new Schedule();
$schedule->run('date')
    ->everyMinute()
    ->sendOutputTo('/tmp/test')
    ->description('test');
return $schedule;

and my /etc/crontab:

* * * * * root /var/www/shield/vender/bin/crunz schedule:run

All my Schedules work fine.
But,When I try to user sendOutputTo(),I get no output in /tmp/test.
It works if I redirect output to file in /etc/crontab:

* * * * * root /var/www/shield/vender/bin/crunz schedule:run >> /tmp/test

So.
How can I send output of each job to individual file.

Thank you.

Force php version

I get a error when the cron is running:

  • * * * * /vendor/bin/crunz schedule:run

PHP Parse error: syntax error, unexpected 'list' (T_LIST) in:
vendor/symfony/config/Definition/ArrayNode.php

It looks like PHP >= 5.5.0 is required.

I have a Debian server running Plesk. When i create a new cron i can select "Run a command" Or "Run a PHP script". For a PHP script i can select a PHP version (default is 5.4).

I can't select a version for "Run a command". How can i force crunz to use PHP 5.6. Or can i start the script bij a php script?

onError function

The onError function is nice. But it would be nice if we could catch / output exceptions in this function so we can log this somewhere or do anything else with them.

Also the ways we can log is way to restricted at this point. I see you use Monolog / LoggerInterface implementation. Perhaps we can make it so the developer can set any logger that implemented the LoggerInterface interface through the config / constructor of his Schedule / Event object?

Undefined variable: input TaskGeneratorCommand.php on line 118

cmd: vendor/bin/crunz make:task demo1 --run demo1.php --in /var/www/html/crunz/tests
exception:
PHP Notice: Undefined variable: input in /var/www/html/crunz/src/Console/Command/TaskGeneratorCommand.php on line 118
PHP Notice: Undefined variable: output in /var/www/html/crunz/src/Console/Command/TaskGeneratorCommand.php on line 118
PHP Catchable fatal error: Argument 1 passed to Symfony\Component\Console\Helper\QuestionHelper::ask() must implement interface Symfony\Component\Console\Input\InputInterface, null given, called in /var/www/html/crunz/src/Console/Command/TaskGeneratorCommand.php on line 118 and defined in /var/www/html/crunz/vendor/symfony/console/Helper/QuestionHelper.php on line 45

Missing dependency on illuminate/console

The method Crunz\Schedule::run creates and returns an Illuminate\Console\Scheduling\Event object, but the illuminate/console package is not required.
Is that correct?

appendOutput to different file

Hi,

I have the following configuration options

log_output: true
output_log_file: app/logs/tasks/general.log

and a task:

$schedule->run('php app/console xxxx')
->everyOneMinutes()
->description('xxxx')
->sendOutputTo('app/logs/tasks/xxx.log');

I would expect the output for this file to be logged to xxx.log, but instead it's logged to general.log.
Same effect when I use appendOutputTo.

Am I missing something?

Event:sudo is not correct

On line https://github.com/lavary/crunz/blob/master/src/Event.php#L200 there is a call to $this->sudo(), but the definition at https://github.com/lavary/crunz/blob/master/src/Event.php#L222-L225 is protected function sudo($user) with the $user parameter being used.

Also, on https://github.com/lavary/crunz/blob/master/src/Event.php#L207 the call to sudo() is not appended to the $command, so nothing will happen with the returned value.

I believe that sudo() should use $this->user as the value and that https://github.com/lavary/crunz/blob/master/src/Event.php#L207 should append it to $command

Class not found error

When I run this on my ubuntu box I get the following error

PHP Fatal error: Class 'Crunz\console\Commands\ScheduleRunCommand' not found in /var/www/xxxx/vendor/lavary/crunz/src/Console/CommandKernel.php on line 31 PHP Stack trace: PHP 1. {main}() /var/www/xxxx/vendor/lavary/crunz/crunz:0 PHP 2. Crunz\Console\CommandKernel->__construct() /var/www/xxxx/vendor/lavary/crunz/crunz:37

Can it be because of small 'c' on 'console'

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.