Giter Club home page Giter Club logo

job-scheduler's Introduction

job-scheduler

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

Job scheduler is a PHP library for scheduling time-based repetitive actions. It uses (RRULE) or Cron notation to configure time and recurrence rule of each job.

Goals

Sometimes amount of cron jobs becomes too large. The main goal is reduce amount of cron jobs to only one.

Installation

Via Composer

$ composer require hutnikau/job-scheduler

Usage

Create recurrence rule

iCalendar syntax

$executionTime = new \DateTime('2017-12-12 20:00:00');
//run monthly, at 20:00:00, 5 times
$rule          = new \Scheduler\Job\RRule('FREQ=MONTHLY;COUNT=5', $executionTime);

Cron syntax:

$executionTime = new \DateTime('2017-12-12 20:00:00');
//run monthly, at 20:00:00
$rule          = new \Scheduler\Job\CronRule('0 20 * 1 *', $executionTime);

Get the recurrences between dates

$dt = new DateTime('2017-12-28T21:00:00');
$dtPlusFiveMinutes = new DateTime('2017-12-28T21:05:00');
$rRule = new CronRule('* * * * *', $dt); //minutely
$rRule->getRecurrences($dt, $dtPlusFiveMinutes); //array with six DateTime instances from '2017-12-28T21:00:00' to '2017-12-28T21:05:00'

Get the next recurrence after given date

$dt = new DateTime('2017-12-28T21:00:00');
$rRule = new CronRule('* * * * *', $dt); //minutely
$rRule->getNextRecurrence($dt); //DateTime instance ('2017-12-28T21:00:00')
//not including given date
$rRule->getNextRecurrence($dt, false); //DateTime instance ('2017-12-28T21:01:00')

Create a job

Job constructor have the following signature: \Scheduler\Job\Job::__construct(RRule $rRule, callable $callable);

Example: iCalendar syntax

$executionTime = new \DateTime('2017-12-12 20:00:00');
//run monthly, at 20:00:00, 5 times
$rule          = new \Scheduler\Job\RRule('FREQ=MONTHLY;COUNT=5', $executionTime);
$job           = new \Scheduler\Job\Job($rule, function () {
    //do something
});

Cron syntax:

$executionTime = new \DateTime('2017-12-12 20:00:00');
//run monthly, at 20:00:00
$rule          = new \Scheduler\Job\CronRule('0 20 * 1 *', $executionTime);
$job           = new \Scheduler\Job\Job($rule, function () {
    //do something
});

Note: Cron syntax does not allow to limit number of occurrences.

Create Job from string using iCalendar syntax:

$job = \Scheduler\Job\Job::createFromString(
    'FREQ=MONTHLY;COUNT=5', //Recurrence rule 
    '2017-12-28T21:00:00',  //Start date
    function() {},          //Callback
    'Europe/Minsk'          //Tmezone. If $timezone is omitted, the current timezone will be used
);

Create Job from string using cron syntax:

$job = \Scheduler\Job\Job::createFromString(
    '0 0 1 * *',            //Cron syntax recurrence rule 
    '2017-12-28T21:00:00',  //Start date
    function() {},          //Callback
    'Europe/Minsk'          //Tmezone. If $timezone is omitted, the current timezone will be used
);

Schedule a job

Scheduler constructor accepts array of jobs as first parameter:

$scheduler = new \Scheduler\Scheduler([
    $job,
    //more jobs here
]);

//also you may add jobs by `\Scheduler\Scheduler::addJob($job)`
$scheduler->addJob($anotherJob);

Run scheduled jobs

Run all jobs scheduled from '2017-12-12 20:00:00' to '2017-12-12 20:10:00':

$jobRunner = new \Scheduler\JobRunner\JobRunner();
$from      = new \DateTime('2017-12-12 20:00:00');
$to        = new \DateTime('2017-12-12 20:10:00');
$reports   = $jobRunner->run($scheduler, $from, $to, true);

Note: the last true parameter means that jobs scheduled exactly at from or to time will be included. In this example it means that jobs scheduled to be run at '2017-12-12 20:00:00' or '2017-12-12 20:10:00' will be executed.

$jobRunner->run(...) returns an array of reports (\Scheduler\Action\Report)

Workers

Worker is supposed to be run continuously and check with defined period if there are jobs to be executed.

$jobRunner = new \Scheduler\JobRunner\JobRunner();
$scheduler = new \Scheduler\Scheduler([
    $job,
    //more jobs here
]);
$worker = new \Scheduler\Worker\Worker($jobRunner, $scheduler);
$worker->setMaxIterations(2);
$worker->run(time(), 'PT1M');

Worker above will make two iterations (checks if there is a job to execute) with an interval of one minute. Default amount of iterations is 1000.

Action inspectors

In order to be able to run two or more workers on different servers or to avoid execution of one job twice action inspectors may be used:

$actionInspector = new \Scheduler\ActionInspector\FileActionInspector('pathToFile');
$jobRunner       = new \Scheduler\JobRunner\JobRunner($actionInspector);
$from            = new \DateTime('2017-12-12 20:00:00');
$to              = new \DateTime('2017-12-12 20:10:00');
$reports         = $jobRunner->run($scheduler, $from, $to, true);

//call of `run` action with the same parameters will not execute any jobs because they already logged by inspecor as finished
//$reports array is empty
$reports         = $jobRunner->run($scheduler, $from, $to, true);

Currently there is also Rds implementation so all the performed actions data can be stored in SQL storage. Constructor of expects to receive \Doctrine\DBAL\Connection instance:

    $actionInspector = new \Scheduler\ActionInspector\RdsActionInspector($connection);

Note: Make sure you prepared the database (created the table) using initDb static method:

    \Scheduler\ActionInspector\RdsActionInspector::initDb($connection);

Reports

\Scheduler\Action\Report class synopsis:

\Scheduler\Action\Report {
    /* Methods */
    public mixed getReport ( void )
    public mixed getAction ( void )
    public mixed getType ( void )
}

In case if during execution an exception has been thrown then this exception will be returned as a result of action.

$report->getType() returns one of two values: \Scheduler\Action\Report::TYPE_SUCCESS | \Scheduler\Action\Report::TYPE_ERROR

Warnings

  1. Be careful with timezones. Make sure that you create \DateTime instances with correct timezone.
  2. Accuracy of scheduler up to seconds. You must be accurate with $from, $to parameters passed to the runner to not miss an action or not launch an action twice (alternatively use action inspectors).
  3. Use \Scheduler\Job\CronRule implementation in case if number of occurrences is not limited.
  4. \Scheduler\Job\RRule implementation is more flexible but in case of large or unlimited number of repeats there may be performance issues. By default limit of \Scheduler\Job\RRule implementation is 732 repeats. More information: https://github.com/simshaun/recurr

Testing

$ composer test

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

job-scheduler's People

Contributors

damner avatar jbout avatar tarampampam avatar tikhanovicha avatar

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.