PHPackages                             surpaimb/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. [Queues &amp; Workers](/categories/queues)
4. /
5. surpaimb/task-balancer

ActiveLibrary[Queues &amp; Workers](/categories/queues)

surpaimb/task-balancer
======================

lightweight and powerful task load balancing.

00PHP

Since Mar 18Pushed 5y ago1 watchersCompare

[ Source](https://github.com/surpaimb/task-balancer)[ Packagist](https://packagist.org/packages/surpaimb/task-balancer)[ RSS](/packages/surpaimb-task-balancer/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependenciesVersions (1)Used By (0)

Intro
=====

[](#intro)

[![Latest Stable Version](https://camo.githubusercontent.com/7cc43339f6959813a33a50f6e75b2ccf176beea4844f50915890f5b122fc9c70/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7375727061696d622f7461736b2d62616c616e6365722e737667)](https://packagist.org/packages/surpaimb/task-balancer)[![Total Downloads](https://camo.githubusercontent.com/6b0f98b53ff89989c9edc9d3c643d8f4e5fae8382c5f102292ac6d69e5623283/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7375727061696d622f7461736b2d62616c616e6365722e737667)](https://packagist.org/packages/surpaimb/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 surpaimb/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/surpaimb/phpsms)

License
=======

[](#license)

MIT

###  Health Score

15

—

LowBetter than 3% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity0

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity30

Early-stage or recently created project

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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/db9f9ae93fc176f3ec8de00c0f6cccda365a5e0b2a01192fc6373663667a7bb7?d=identicon)[surpaimb](/maintainers/surpaimb)

### Embed Badge

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

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

###  Alternatives

[league/geotools

Geo-related tools PHP 7.3+ library

1.4k5.3M26](/packages/league-geotools)[amphp/parser

A generator parser to make streaming parsers simple.

14952.8M16](/packages/amphp-parser)[amphp/serialization

Serialization tools for IPC and data storage in PHP.

13451.1M18](/packages/amphp-serialization)[enqueue/enqueue

Message Queue Library

19820.0M56](/packages/enqueue-enqueue)[deliciousbrains/wp-background-processing

WP Background Processing can be used to fire off non-blocking asynchronous requests or as a background processing tool, allowing you to queue tasks.

1.1k409.8k6](/packages/deliciousbrains-wp-background-processing)[react/async

Async utilities and fibers for ReactPHP

2238.8M171](/packages/react-async)

PHPackages © 2026

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