Skip to content

Limits, deadlines and errors in tasks

Core\Task::all and Core\Task::map take an options object as the last argument. It has two optional fields, limit and deadline.

limit and deadline

Core\Task::all and Core\Task::map both take a second argument with two fields, limit and deadline. Both fields are optional, and they are the only two bounds a group of tasks has.

limit says how many tasks may run at the same time. The others wait for a free place, and none of them is refused. Without a limit, every task starts at once. A limit of 0 throws LogicError.

deadline is a time limit for the whole call, not for each task. When it passes, every task still running is stopped. The call waits for those tasks to stop, and then throws TimeoutError. A stopped task runs no more of its own code: not its catch, and not the line after the one it was waiting on.

The examples below show a deadline for a whole call, two tasks running at a time, and a price list that is polite to a slow service.

A deadline for the whole call

<?nvs
// Shows how to give a group of tasks a time limit. The deadline covers the whole
// call. When it passes, every task still running is stopped and the call throws
// `TimeoutError`.
try {
Core\Task::all({
quick: fn(): int => 1,
slow: fn(): int => {
Core\Time::sleep(500ms);
return 2;
},
}, { deadline: 20ms });
echo "both tasks finished\n";
} catch (TimeoutError $late) {
// This is the line that prints. `slow` needs half a second, and the group has
// 20 milliseconds.
echo "the group ran out of time\n";
}
Output
the group ran out of time

No more than two tasks at a time

<?nvs
// Shows how to say how many tasks may run at the same time. There are six tasks
// here, and `limit` lets two of them run at once. The other four wait for a free
// place. None of them is refused.
class Gauge
{
public static int $running = 0;
public static int $most = 0;
}
var $results = Core\Task::map(Core\Arr::range(1, 6), fn(int $n): int => {
Gauge::$running += 1;
if (Gauge::$running > Gauge::$most) {
Gauge::$most = Gauge::$running;
}
Core\Time::sleep(5ms);
Gauge::$running -= 1;
return $n * 10;
}, { limit: 2 });
// This prints 2. Two tasks ran at the same time, and never three.
echo 'most at once: ', Gauge::$most, "\n";
// All six tasks ran, so the last result is 60.
echo 'last result: ', $results[5], "\n";
Output
most at once: 2
last result: 60

A price list that is polite and gives up

<?nvs
// Shows a real use: a report needs the price of six products from a slow service.
// `limit` asks for no more than two prices at a time, so the service is not flooded.
// `deadline` stops the whole report after one second.
class Prices
{
public static function of(string $sku): int
{
// A real program asks another server here.
Core\Time::sleep(5ms);
return Core\Str::length($sku) as int * 100;
}
}
array<string> $skus = ['cup', 'mug', 'kettle', 'spoon', 'pot', 'tray'];
try {
var $prices = Core\Task::map(
$skus,
fn(string $sku): int => Prices::of($sku),
{ limit: 2, deadline: 1s },
);
foreach ($prices as int $price) {
echo $price, "\n";
}
} catch (TimeoutError $late) {
// The report prints this when the service does not answer in time.
echo "the price service was too slow\n";
}
Output
300
300
600
500
300
400

Details

The options must be written at the call as {…}. Options kept in a variable are E0453. A field that is not limit or deadline is E0454, and its help lists the two.

limit is a uint. limit: -1 and an int variable are E0401. A limit larger than the number of tasks is allowed. The waiting tasks start in the order they were written.

deadline is a Core\Time\Duration, such as 20ms. A number such as 20 is E0401.

The TimeoutError message is Core\Task::map: the deadline expired before every child returned, with Core\Task::all for that call. TimeoutError is a RuntimeError. The LogicError message for limit: 0 starts with Core\Task::map: or Core\Task::all: too.

deadline: 0ms throws TimeoutError, even when no task waits.

A stopped task does not run its finally blocks either.

A task can start its own group with a shorter deadline, and catch that group's TimeoutError. The outer group then goes on. When the outer deadline passes first, it stops the inner groups too, and the outer call throws its own TimeoutError.

When a task throws

Core\Task::all and Core\Task::map run several tasks at the same time. When one task throws an error, the whole group stops.

The first error wins. The other tasks are cancelled, and none of them is still running when your catch runs. The error you catch is the one the task threw. It has the same class, the same message, and your own properties if you wrote your own error class. Nothing wraps it.

A cancelled task runs nothing more. Its own catch does not run, and neither do the lines after it.

The examples below show a group where one task fails, an error class of your own crossing out of a task, a page that loads three things and reports the one that was missing, and two tasks that throw before they wait.

One task fails and the group stops

<?nvs
// Shows what happens when one task in a group throws an error. The group stops
// and your `catch` gets the error that task threw.
class Trace
{
public static int $finished = 0;
}
try {
Core\Task::all({
// This task waits, so the other one throws first.
slow: fn(): int => {
Core\Time::sleep(2s);
Trace::$finished = Trace::$finished + 1;
return 1;
},
quick: fn(): int => {
throw new RuntimeError('the price list is empty');
},
});
echo "the group finished\n";
} catch (RuntimeError $e) {
echo 'caught: ', $e->message, "\n";
}
// The slow task was cancelled, so it never reached its last line.
echo Trace::$finished, " tasks finished\n";
Output
caught: the price list is empty
0 tasks finished

An error class of your own

<?nvs
// Shows an error class of your own crossing out of a task. The class and the
// properties you gave it are still there in the `catch`.
class ImportFailed extends RuntimeError
{
public int $row;
public function constructor(string $message, int $row)
{
$this->row = $row;
parent::constructor($message);
}
}
try {
// One task for each file. The second file has a row this program cannot read.
Core\Task::map([1, 2, 3], fn(int $file): int => {
if ($file == 2) {
throw new ImportFailed('this row has no price', 31);
}
return $file;
});
echo "all three files were imported\n";
} catch (ImportFailed $e) {
echo $e->message, "\n";
echo 'row ', $e->row, "\n";
}
Output
this row has no price
row 31

A page that loads three things

<?nvs
// Shows a page that loads three things at the same time. One of them is not
// there, so the page says so instead of showing half of itself.
class Store
{
public static function user(): string
{
return 'Ada';
}
public static function orders(): int
{
return 3;
}
public static function recommendations(): int
{
throw new RuntimeError('the recommendation service is down');
}
}
try {
var $page = Core\Task::all({
user: fn(): string => {
return Store::user();
},
orders: fn(): int => {
return Store::orders();
},
recommendations: fn(): int => {
return Store::recommendations();
},
});
echo $page->user, ' has ', $page->orders, " orders\n";
} catch (RuntimeError $e) {
echo 'this page cannot be built: ', $e->message, "\n";
}
Output
this page cannot be built: the recommendation service is down

Two tasks throw before they wait

<?nvs
// Shows two tasks that both throw before they wait for anything. Your `catch` gets
// the first error.
try {
Core\Task::all({
first: fn(): int => {
throw new RuntimeError('the first file is missing');
},
// This task runs before the group can stop it. Its error is printed on
// standard error, and your program goes on.
second: fn(): int => {
echo "the second task started\n";
throw new RuntimeError('the second file is missing');
},
});
} catch (RuntimeError $e) {
echo 'caught: ', $e->message, "\n";
}
echo "the program goes on\n";
Output
the second task started
caught: the first file is missing
the program goes on

Details

A task runs until it waits, for example in Core\Time::sleep or a send on a full channel. The other tasks are stopped at the place where they wait. A task that throws before it waits for anything is not stopped in time. When two tasks throw that way, your catch gets the first error. The second error is printed on standard error as uncaught in a cancelled sibling: second, and the program goes on. With Core\Task::map, the first error is the one of the first element.

A stopped task runs none of its own catch and finally blocks. What it printed before it stopped is still printed.

The error you catch is the same object the task threw. == with a copy the task saved is true. A catch (Throwable $e) gets it too, and $e is LogicError is still true for a LogicError.

The backtrace of the error has one entry: the task's function, at the line of the throw.

A task can start its own group. An error in the inner group passes through the outer group to your catch, and the other tasks of the outer group are stopped too.

When nothing catches the error, the program ends with exit status 1 and the usual error report.

When a deadline passes before any task throws, the call throws TimeoutError, and the later error is not thrown.

  • Do set limit when each task uses something scarce, like a database connection.
  • Do set deadline when your program must not wait too long for a slow server.
  • Do catch TimeoutError around a call with a deadline.
  • Don’t put a try inside each task only to stop the others. Novis already stops them.