PHPackages                             toplan/task-balancer - 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. toplan/task-balancer

ActiveLibrary

toplan/task-balancer
====================

lightweight and powerful task load balancing.

0.5.0(8y ago)46119.1k↓100%111MITPHPPHP &gt;=5.4.0

Since Nov 12Pushed 8y ago2 watchersCompare

[ Source](https://github.com/toplan/task-balancer)[ Packagist](https://packagist.org/packages/toplan/task-balancer)[ RSS](/packages/toplan-task-balancer/feed)WikiDiscussions master Synced today

READMEChangelog (10)DependenciesVersions (20)Used By (1)

Intro
=====

[](#intro)

[![Latest Stable Version](https://camo.githubusercontent.com/236c85884bb3e970a42cca10c1cafd5bbab8a5b3d0d2042aa78221c928f39b46/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f706c616e2f7461736b2d62616c616e6365722e737667)](https://packagist.org/packages/toplan/task-balancer)[![Total Downloads](https://camo.githubusercontent.com/8df357a96b4b432cca6c18d2177c57e86700160678df937b14aeb85756bd4181/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f706c616e2f7461736b2d62616c616e6365722e737667)](https://packagist.org/packages/toplan/task-balancer)

Lightweight and powerful task load balancing.

> like the `nginx` load balancing 😄

Features
========

[](#features)

- Support multiple drives for every task.
- Automatically choose a driver to execute task by drivers' weight value.
- Support multiple backup drivers.
- Task lifecycle and hooks system.

Install
=======

[](#install)

```
composer require toplan/task-balancer:~0.5
```

Usage
=====

[](#usage)

```
//define a task
Balancer::task('task1', function($task){
    //define a driver for current task like this:
    $task->driver('driver_1 100 backup', function ($driver, $data) {
        //do something here
        ...
        //set whether run success/failure at last
        if ($success) {
            $driver->success();
        } else {
            $driver->failure();
        }
        //return some data you need
        return 'some data you need';
    });

    //or like this:
    $task->driver('driver_2', 90, function ($driver, $data) {
        //...same as above..
    })->data(['this is data 2']);

    //or like this:
    $task->driver('driver_3')
    ->weight(0)->backUp()
    ->data(['this is data 3'])
    ->work(function ($driver, $data) {
        //...same as above..
    });
});

//run the task
$result = Balancer::run('task1');
```

The `$result` structure:

```
[
    'success' => true,
    'time' => [
        'started_at' => timestamp,
        'finished_at' => timestamp
    ],
    'logs' => [
        '0' => [
            'driver' => 'driver_1',
            'success' => false,
            'time' => [
                'started_at' => timestamp,
                'finished_at' => timestamp
            ],
            'result' => 'some data you need'
        ],
        ...
    ]
]
```

API
===

[](#api)

Balancer
--------

[](#balancer)

### Balancer::task($name\[, $data\]\[, Closure $ready\]);

[](#balancertaskname-data-closure-ready)

Create a task instance, and return it. The closure `$ready` immediately called with argument `$task`.

```
Balancer::task('taskName', $data, function($task){
    //task's ready work, such as create drivers.
});
```

> `$data` will store in the task instance.

### Balancer::run($name\[, array $options\])

[](#balancerrunname-array-options)

Run the task by name, and return the result data.

The keys of `$options`:

- `data`
- `driver`

Task
----

[](#task)

### name($name)

[](#namename)

set the name of task.

### data($data)

[](#datadata)

Set the data of task.

### driver($config\[, $weight\]\[, 'backup'\], Closure $work)

[](#driverconfig-weight-backup-closure-work)

Create a driver for the task. The closure `$work` will been called with arguments `$driver` and `$data`.

> Expected `$weight` to be a integer, default `1`.

```
$task->driver('driverName 80 backup', function($driver, $data){
    //driver's job content.
});
```

### hasDriver($name)

[](#hasdrivername)

Whether has the specified driver.

### getDriver($name)

[](#getdrivername)

Get driver by name.

### removeDriver($name)

[](#removedrivername)

Remove driver from drivers' pool by name.

Driver
------

[](#driver)

### weight($weight)

[](#weightweight)

Set the weight value of driver.

### backup($is)

[](#backupis)

Set whether backup driver.

> Expected `$is` to be boolean, default `true`.

### data($data)

[](#datadata-1)

Set the data of driver.

> `$data` will store in driver instance.

### work(Closure $work);

[](#workclosure-work)

Set the job content of driver.

> `$data` equals to `$driver->getData()`

### reset($config\[, $weight\]\[, 'backup'\], Closure $work)

[](#resetconfig-weight-backup-closure-work)

Reset driver's weight value, job content and reset whether backup.

### destroy()

[](#destroy)

Remove the driver from task which belongs to.

### failure()

[](#failure)

Set the driver running failure.

### success()

[](#success)

Set the driver run successfully.

### getDriverData()

[](#getdriverdata)

Get the data which store in driver instance.

### getTaskData()

[](#gettaskdata)

Get the data which store in task instance.

Lifecycle &amp; Hooks
---------------------

[](#lifecycle--hooks)

> Support multiple handlers for every hooks!

### Hooks

[](#hooks)

Hook namehandler argumentsinfluence of the last handler's return valuebeforeCreateDriver$task, $props, $index, &amp;$handlers, $prevReturnif an array will been merged into original propsafterCreateDriver$task, $driver, $index, &amp;$handlers, $prevReturn-beforeRun$task, $index, &amp;$handlers, $prevReturnif `false` will stop run task and return `false`beforeDriverRun$task, $driver, $index, &amp;$handlers, $prevReturnif `false` will stop to use current driver and try to use next backup driverafterDriverRun$task, $driverResult, $index, &amp;$handlers, $prevReturn-afterRun$task, $taskResult, $index, &amp;$handlers, $prevReturnif not boolean will override result value### Usage

[](#usage-1)

- $task-&gt;hook($hookName, $handler, $override)
- $task-&gt;beforeCreateDriver($handler, $override)
- $task-&gt;afterCreateDriver($handler, $override)
- $task-&gt;beforeRun($handler, $override)
- $task-&gt;beforeDriverRun($handler, $override)
- $task-&gt;afterDriverRun($handler, $override)
- $task-&gt;afterRun($handler, $override)

> `$override` default `false`.

```
//example
$task->beforeRun(function($task, $index, $handlers, $prevReturn){
    //what is $prevReturn?
    echo $prevReturn == null; //true
    //what is $index?
    echo $index == 0; //true
    //what is $handlers?
    echo count($handlers); //2
    //do something..
    return 'beforeRun_1';
}, false);

$task->beforeRun(function($task, $index, $handlers, $prevReturn){
    //what is $prevReturn?
    echo $prevReturn == 'beforeRun_1'; //true
    //what is $index?
    echo $index == 1; //true
    //what is $handlers?
    echo count($handlers); //2
    //do other something..
}, false);
```

Dependents
==========

[](#dependents)

- [phpsms](https://github.com/toplan/phpsms)

License
=======

[](#license)

MIT

###  Health Score

37

—

LowBetter than 84% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity43

Moderate usage in the ecosystem

Community14

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 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 ~32 days

Recently: every ~109 days

Total

18

Last Release

3234d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1b598ead57cbabafb3d2eea7db7901e3f51a37108750cc2552fc468c3364ee21?d=identicon)[toplan](/maintainers/toplan)

---

Top Contributors

[![toplan](https://avatars.githubusercontent.com/u/7815594?v=4)](https://github.com/toplan "toplan (73 commits)")

---

Tags

balancingloadbalancingtask-runnerload balancingtaskbalance

### Embed Badge

![Health badge](/badges/toplan-task-balancer/health.svg)

```
[![Health](https://phpackages.com/badges/toplan-task-balancer/health.svg)](https://phpackages.com/packages/toplan-task-balancer)
```

###  Alternatives

[fideloper/proxy

Set trusted proxies for Laravel

7.3k173.7M521](/packages/fideloper-proxy)[phing/phing

PHing Is Not GNU make; it's a PHP project build system or build tool based on Apache Ant.

1.2k21.4M801](/packages/phing-phing)[hhxsv5/laravel-s

🚀 LaravelS is an out-of-the-box adapter between Laravel/Lumen and Swoole.

3.9k670.9k10](/packages/hhxsv5-laravel-s)[ruckusing/ruckusing-migrations

Framework for generating and managing database migrations

503994.4k8](/packages/ruckusing-ruckusing-migrations)[jmose/command-scheduler-bundle

This Symfony bundle will allow you to schedule all your commands just like UNIX crontab

3301.4M1](/packages/jmose-command-scheduler-bundle)[robersonfaria/laravel-database-schedule

Manage your Laravel Task Scheduling in a friendly interface and save schedules to the database.

332112.3k](/packages/robersonfaria-laravel-database-schedule)

PHPackages © 2026

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