1 | | | import '../stats/worker_stat.dart'; |
2 | | | import '../worker/worker.dart'; |
3 | | | import '_worker_task.dart'; |
4 | | | import 'worker_pool.dart'; |
5 | | |
|
6 | | | /// Class representing a [Worker] from a [WorkerPool]. |
7 | | | class PoolWorker<W extends Worker> { |
8 | | | /// Constructs a new [PoolWorker]. |
9 | | 8 | PoolWorker(this.worker, this._maxWorkload) : _capacity = _maxWorkload; |
10 | | |
|
11 | | | /// The [Worker] associated to this [PoolWorker]. |
12 | | | final W worker; |
13 | | |
|
14 | | | final int _maxWorkload; |
15 | | | int? _lastStart; |
16 | | | int _capacity; |
17 | | |
|
18 | | | /// The current capacity of this [PoolWorker]. |
19 | | 12 | int get capacity => _capacity; |
20 | | |
|
21 | | | /// Whether this [PoolWorker] is stopped or doing nothing. |
22 | | 7 | bool get isIdle => worker.isStopped || _capacity == _maxWorkload; |
23 | | |
|
24 | | | /// Run the specified [task] in the [worker]. |
25 | | 8 | Future<void> run(WorkerTask task) { |
26 | | 16 | _lastStart = DateTime.now().millisecondsSinceEpoch; |
27 | | 8 | _capacity--; |
28 | | 20 | return task.run(worker).whenComplete(() { |
29 | | 12 | _capacity++; |
30 | | 16 | if (_capacity == _maxWorkload) { |
31 | | 8 | _lastStart = null; |
32 | | | } |
33 | | 4 | }); |
34 | | 4 | } |
35 | | |
|
36 | | | /// Compares [PoolWorker] instances by capacity (descending) and last execution (ascending). |
37 | | 6 | static int compareCapacityDesc(PoolWorker a, PoolWorker b) { |
38 | | 21 | if (a.capacity != b.capacity) return b.capacity.compareTo(a.capacity); |
39 | | 6 | if (a._lastStart == null) return 1; |
40 | | 6 | if (b._lastStart == null) return -1; |
41 | | 12 | return a._lastStart!.compareTo(b._lastStart!); |
42 | | 3 | } |
43 | | |
|
44 | | 16 | static bool isStopped(PoolWorker w) => w.worker.isStopped; |
45 | | 4 | static WorkerStat getStats(PoolWorker w) => w.worker.stats; |
46 | | | } |