PHPackages                             caseyamcl/tasktracker - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [CLI &amp; Console](/categories/cli)
4. /
5. caseyamcl/tasktracker

ActiveLibrary[CLI &amp; Console](/categories/cli)

caseyamcl/tasktracker
=====================

A PHP library for keeping track of progress and stats for long running tasks

2.2.4(7y ago)4511[5 issues](https://github.com/caseyamcl/tasktracker/issues)MITPHPPHP &gt;=5.4|^7.0

Since Apr 4Pushed 9mo ago1 watchersCompare

[ Source](https://github.com/caseyamcl/tasktracker)[ Packagist](https://packagist.org/packages/caseyamcl/tasktracker)[ Docs](http://github.com/caseyamcl/tasktracker)[ RSS](/packages/caseyamcl-tasktracker/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (8)Dependencies (6)Versions (11)Used By (0)

Task Tracker
============

[](#task-tracker)

**A library for tracking long-running tasks in PHP (when a simple progress bar isn't enough)**

[![Latest Version](https://camo.githubusercontent.com/8482b8c8676a083db0087b104f757a1582d3106d7452b0be05f504c56e0ab55e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f6361736579616d636c2f7461736b747261636b65722e7376673f7374796c653d666c61742d7371756172653f7374796c653d666c61742d737175617265)](https://github.com/caseyamcl/tasktracker/releases)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/528ed8e8348f7fa81a95cfe0c6c1c8c33638efa49d5d7edf2bdf6f456e16084e/68747470733a2f2f7472617669732d63692e6f72672f6361736579616d636c2f7461736b747261636b65722e706e67)](https://travis-ci.org/caseyamcl/tasktracker)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/bcfb6408d8c48b1ac9253869d8902c0ada78f6a0019dde3d1ef91657ff765dd3/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6361736579616d636c2f7461736b747261636b65722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/caseyamcl/tasktracker/?branch=master)

**At a Glance**:

- Reports on memory usage and a number of progress statistics during long-running tasks
- Useful for long-running processes where a large number of small jobs are executed
- Event-driven architecture using the [Symfony Event-Dispatcher Component](http://symfony.com/doc/current/components/event_dispatcher/introduction.html)
    - Can report on task progress to any [EventSubscriberInterface](http://symfony.com/doc/current/components/event_dispatcher/introduction.html#using-event-subscribers)
- Provides built-in utilities for reporting task progress:
    - Symfony Console Progress Bar
    - Symfony Console Running Log of Task Messages
    - Sending Task Progress to [PSR-3 Compatible Loggers](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)

For example, you may want to display a progress bar on the console during execution of a task, but also send periodic snapshots of the state of the system to Monolog while a task is executing. Using a single Tracker object, you can accomplish both of these goals:

```
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use TaskTracker\Subscriber\SymfonyConsoleLog;
use TaskTracker\Tracker;
use TaskTracker\Tick;
use TaskTracker\Subscriber\SymfonyConsoleProgress;
use TaskTracker\Subscriber\Psr3Logger;
use Monolog\Logger as MonologLogger;

require_once __DIR__ . '/vendor/autoload.php';

$consoleOutput = new ConsoleOutput(OutputInterface::VERBOSITY_DEBUG);

// Setup subscribers
$subscribers = [
    // new SymfonyConsoleProgress($consoleOutput), // tick();
}
$tracker->finish("All done");
```

Installation
------------

[](#installation)

Install via Composer:

```
composer require caseyamcl/tasktracker:~2.0

```

Install manually:

1. Download the source from .
2. Include the `src/TaskTracker` folder in your code using a PSR-4 compatible autoloader.

Usage
-----

[](#usage)

To track a task, create an instance of the `Tracker` class:

```
use TaskTracker\Tracker;

// Instantiate a tracker to track 100 items
$tracker = new Tracker(100);

```

You can omit the number of items if you are working with an unknown number:

```
$tracker = new Tracker();

```

The `Tracker` class creates its own `EventDispatcher`, but you can optionally inject your own if you need to:

```
$dispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();

$tracker = new Tracker(100, $dispatcher);
// ..or..
$tracker = new Tracker(Tracker::UNKNOWN, $dispatcher);

```

To start tracking, simply call the `Tracker::start()` method:

```
// Start the tracker
$tracker->start('optional starting message');

```

For every element you process, call the `Tracker::tick()` method until you are done:

```
// Tick
$tracker->tick();

```

There are three types of Ticks: *Success* (default), *Fail*, and *Skip*:

```
use Tracker\Tick;

$tracker->tick(Tick::SUCCESS);
$tracker->tick(Tick::FAIL);
$tracker->tick(Tick::SKIP);

```

You can also supply an optional message:

```
$tracker->tick(Tick::SUCCESS, 'Things are going well.');
$tracker->tick(Tick::FAIL,    'Crud.  Something went wrong');
$tracker->tick(Tick::SKIP,    'Skipping this record for whatever reason');

```

You can add custom data to the Tick in the form of an array:

```
$tracker->tick(Tick::SUCCESS, 'Things are going well.', ['foo' => 'bar', 'baz' => 'biz]);

```

And, you can increment by more than one item at a time:

```
// Increment by 5 items
$tracker->tick(Tick::SUCCESS, '', [], 5);

// Three items failed
$tracker->tick(Tick::FAIL, 'Something went wrong', [], 3);

```

When you are done, call the `Tracker::finish()` method:

```
$tracker->finish('Optional finish manage');

```

Or, if things go wrong during processing, you can abort:

```
$tracker->abort('Optional abort message');

```

The class contains a few helper methods, too:

```
// Have we started processing yet?
$tracker->isRunning();

// Get the last tick (instance of \Tracker\Tick class)
$tracker->getLastTick();

// Get the status of the process as an int (Tracker::NOT_STARTED, Tracker::RUNNING, Tracker::FINISHED, or Tracker::ABORTED)
$tracker->getStatus();

// Get the number of items processed thus far
$tracker->getNumProcessedItems();

// Get only the number of failed items (works with SUCCESS and SKIP too)
$tracker->getNumProcessedItems(Tick::FAIL);

// Get the time started (in microseconds)
$tracker->getStartTime();

```

You can use the `Tracker:run($iterator, $callback)` method for cleaner syntax.
The `$iterator` value must be an instance of `\Traversable`; arrays are not accepted, but `ArrayIterator` objects will work:

```
$iterator = new \ArrayIterator(['a', 'b', 'c']);

// This code is the equivalent of...
$tracker->run($iterator, function(Tracker $tracker, $item) {
    // work on a single item
    $tracker->tick();
});

//...this code:
$tracker->start();
foreach ($iterator as $item) {
    // work on a single item
    $tracker->tick();
}
$tracker->finish();

```

### Subscribers

[](#subscribers)

The `Tracker` class isn't very useful on its own without event subscribers to listen for tracker tick events. There are a few subscribers bundled with this library:

- `TaskTracker\Subscriber\Psr3Logger` - Logs Tracker events to any [PSR-3 Logger](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)
- `TaskTracker\Subscriber\SymfonyConsoleLog` - Logs Tracker events to a Symfony console, each event on its own line.
- `TaskTracker\Subscriber\SymfonyConsoleProgress` - Logs tracker events to a Symfony console progress bar indicator.

You can add event subscribers to the Tracker by calling the `Tracker::addSubscriber()` method:

```
$tacker = new Tracker(100);
$tracker->addSubscriber(new SymfonyConsoleLog($output));

```

If you know what subscribers you will use ahead of time, you can use the `Tracker::build()` method for convenience:

```
$subscribers = [new SymfonyConsoleLog($output), new SomeOtherSubscriber()];
$tracker = Tracker::build(100, $subscribers);

```

### Example

[](#example)

As an example, suppose you are creating a Symfony Console Command, and you want to show a progress bar for some task and also log events as they occur:

```
use TaskTracker\Tracker;
use TaskTracker\Tick;
use TaskTracker\Subscriber\SymfonyConsoleProgress;
use Symfony\Component\Console\Command\Command;

/**
 * My Symfony Command
 */
class MyCommand extends Command
{
    protected function configure()
    {
        $this->setName('example');
        $this->setDescription("Demonstrate TaskTracker");
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $numItems = 10;

        // Build Task Tracker with Symfony Console Progress Bar subscriber
        $tracker = Tracker::build([new SymfonyConsoleProgress($output)], $numItems);

        // Add a Monolog Listener after Tracker construction
        $monolog = new \Monolog\Logger(/* some handlers */);
        $tracker->addSubscriber(new Psr3Logger($monolog));

        // You can also add Event Listeners directly
        $tracker->getDispatcher()->addListener(\Tracker\Events::TRACKER_TICK, function(\Tracker\Tick $tick) {
            // do something...
        });

        // Tracker::start() is technically optional; if not called, it will automatically
        // be called upon the first Tick
        $tracker->start("Let's go!");

        // The SymfonyConsoleProgress listener will output a progress bar while the logger will log events
        for ($i = 0; $i < 10; $i++) {
            $tracker->tick(\Tick::SUCCESS, "On item: " . $i);
            sleep(1);
        }

        // Tracker::start(), Tracker::tick(), Tracker::abort(), and Tracker::finish() all return
        // a \Tracker\Report object.
        $report = $tracker->finish('All done!');

        $output->writeln(sprintf("All Done!  %s items processed", $report->getNumTotalItems()));
    }
}
```

### Custom Subscribers

[](#custom-subscribers)

TaskTracker uses the [Symfony EventDispatcher](http://symfony.com/doc/current/components/event_dispatcher/introduction.html)library, so any Symfony-compatible event listener can be used.

There are four events you can listen for:

- `TaskTracker\Events::TRACKER_START`
- `TaskTracker\Events::TRACKER_TICK`
- `TaskTracker\Events::TRACKER_FINISH`
- `TaskTracker\Events::TRACKER_ABORT`

All four events dispatch an instance of the `TaskTracker\Tick` class. Your subscribers/listeners should accept an object of that class as its parameter:

```
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use TaskTracker\Tick;

/**
 * Listen for Tracker Events
 */
class MyEventSubscriber implements EventSubscriberInterface
{
     public static function getSubscribedEvents()
     {
         return [
             TaskTracker\Events::TRACKER_START  => 'handle',
             TaskTracker\Events::TRACKER_TICK   => 'handle',
             TaskTracker\Events::TRACKER_FINISH => 'handle',
         ];
     }

     public static function handle(Tick $tickEvent)
     {
         // See all of the information about the progress of that tick
         var_dump($tickEvent->getReport()->toArray());
     }
}
```

### Reports

[](#reports)

Every Tracker event emits a `\Tracker\Report` object with a snapshot of the process and some system information present at the point in time that the event occurred:

```
$report = $tracker->tick();

$report->getTimeStarted();
$report->getTotalItemCount();
$report->getTick();
$report->getNumItemsProcessed();
$report->getTimeElapsed();
$report->getNumItemsSuccess();
$report->getNumItemsFail();
$report->getNumItemsSkip();
$report->getItemTime();
$report->getMaxItemTime();
$report->getMinItemTime();
$report->getAvgItemTime();
$report->getMemUsage();
$report->getMemPeakUsage();
$report->getMessage();
$report->getTimestamp();
$report->getStatus();
$report->getIncrementBy();
$report->getReport();
$report->getExtraInfo();
```

In your subscribers, you can access the report from the `Tick` object by calling `Tick::getReport()`.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance21

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~274 days

Recently: every ~296 days

Total

9

Last Release

2594d ago

Major Versions

v1.0 → v2.02015-03-19

PHP version history (3 changes)v1.0PHP &gt;=5.3.1

v2.0PHP &gt;=5.4

v2.2.2PHP &gt;=5.4|^7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/8db51cd614310a5de4822be9602de578e6d6dd2af7949d52fcd375ba2a8d1c74?d=identicon)[caseyamcl](/maintainers/caseyamcl)

---

Top Contributors

[![caseyamcl](https://avatars.githubusercontent.com/u/53035?v=4)](https://github.com/caseyamcl "caseyamcl (96 commits)")

---

Tags

asynchronousclinegotiationreporttaskprogresstasktracker

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/caseyamcl-tasktracker/health.svg)

```
[![Health](https://phpackages.com/badges/caseyamcl-tasktracker/health.svg)](https://phpackages.com/packages/caseyamcl-tasktracker)
```

###  Alternatives

[cilex/cilex

The PHP micro-framework for Command line tools based on the Symfony2 Components

6183.2M15](/packages/cilex-cilex)[n98/magerun

Tools for managing Magento projects and installations

1.4k264.7k7](/packages/n98-magerun)[n98/magerun2

Tools for managing Magento projects and installations

928244.3k6](/packages/n98-magerun2)[seregazhuk/php-watcher

Automatically restart PHP application once the source code changes

394137.8k4](/packages/seregazhuk-php-watcher)[laminas/laminas-cli

Command-line interface for Laminas projects

563.7M54](/packages/laminas-laminas-cli)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
