5. A task that takes long
An import of fifty thousand rows does not fit into one run of a tool. The browser waits, PHP's time limit ends the script, and nobody sees how far it is. Work like that belongs to a worker: a job in a queue, a cron job, a command. The tool starts the task and then shows how far it is.
The tool and the worker never talk to each other. They share one row in your storage. The worker writes how far it is, and the page reads that row every two seconds.
The tool of the demo
The export of the demo takes half a minute. Its clock stands in for a worker, and everything else is what a real tool does:
<?php
// Export orders
// A task that takes long: start it, watch how far it is, stop it, fetch the file. Or see it fail.
require_once __DIR__ . '/_export.php';
use function Runio\ScriptUi\{title, note, progress, refresh, button, checkbox, download, success, warning, error, rerun};
title('Export orders');
$export = Export::read(); // the export belongs to the shop: whoever opens this page sees the same one
if ($export->state === 'waiting' || $export->state === 'running') {
// The work goes on somewhere else. This page looks at it every two seconds, for as long as it is open.
refresh(2);
if ($export->state === 'waiting') {
// No value: nobody knows yet how far it is.
progress('Waiting for a worker');
} else {
progress('Exporting orders', $export->done, Export::ORDERS, text: number_format($export->done) . ' of ' . number_format(Export::ORDERS) . ' orders');
}
if (button('Stop the export', confirm: 'Stop the export where it is?')) {
Export::stop();
rerun();
}
return;
}
if ($export->state === 'finished') {
success(number_format($export->done) . ' orders are exported.');
download('Download orders.csv', Export::orders(...), 'orders.csv');
} elseif ($export->state === 'stopped') {
warning('The export was stopped at ' . number_format($export->done) . ' of ' . number_format(Export::ORDERS) . ' orders.');
} elseif ($export->state === 'failed') {
// A short message of your own. What the worker threw is in its log: it names paths and queries.
error('The export failed at ' . number_format($export->done) . ' of ' . number_format(Export::ORDERS) . ' orders. There is no file to download.');
} else {
note('An export of all orders takes about half a minute. In a real shop a worker would write it. Here the clock stands in for the worker.');
}
// Only the demo asks this. Its clock cannot fail, and a real worker needs no help with that.
$fails = checkbox('Let the worker give up half way', help: 'To see what a failed export looks like.');
if (button($export->state === 'none' ? 'Start the export' : 'Start a new export', style: 'primary')) {
// Hands the work over and comes back at once. No message: the bar on the next page says that it started.
Export::start($fails);
rerun();
}
Lines 13 to 15. While the task waits or runs, refresh(2) runs the script again every two seconds. When the task is over, the script no longer reaches that line, and the page stands still.
Lines 17 to 22. progress() without a value says only that work is going on: nobody knows yet how far it is. With two numbers it draws a bar, and text: puts your own words beside it in place of the percentage.
Lines 24 to 27. Stopping is a wish. The button writes it down, and the worker looks for it between two steps.
Lines 37 to 39. A task that failed shows error() in place of the bar, with a short message of your own. The script no longer reaches refresh(), so the page stands still, as it does for a task that finished or was stopped. What the worker threw is not shown: it names paths and queries, and belongs into your log.
Lines 44 and 45. Only the demo has this box. Its clock cannot fail, so a tick asks it to give up half way, and you can see the failed state without breaking anything. A real worker writes "failed" into the row by itself, when something throws.
Lines 47 to 51. The start hands the work over and comes back at once. It writes no message: the bar on the next page says that the task started.
What the tool shows in each state
The demo shows all five. To see the failed one, tick "Let the worker give up half way" before you start the export: it fails at 1,200 of 2,400 orders, about fifteen seconds later.
What to think of
The rest of this page is the text of the README, word for word.
progress() draws a label, a bar and a percentage from the two numbers it gets in this run. It keeps nothing, returns nothing and does not move by itself. refresh(2) is what moves it: the script runs again every two seconds and reads the numbers anew. When the task is over the script no longer reaches refresh(), and the page stands still.
progress('Waiting for a worker'), without a value, draws a bar that only says that work is going on. Amax:of 0 or less does the same, and so doesNANorINF: a task that has not counted its rows yet has not done all of them.- The value counts up to the third argument, and up to 100 without one:
progress('Disk', 73). More than that counts as all of it, and less than 0 as nothing. The percentage is cut and not rounded, so it says "100%" only when all of it is done. Both are numbers: a script withstrict_typescasts what a database hands it as text,(int) $row['done']. text:puts your own words beside the bar in place of the percentage, and a screen reader says them for the value:progress('Importing orders', 1200, 3000, text: '1,200 of 3,000 orders'). The time that is left belongs there too when you know it.- A bar is not an input. It has no key, a link cannot set it, and a page may show several. Its label is its name, for a screen reader too, so an empty label is an error.
The task is yours. The library starts no worker and keeps no task. A worker writes down how far it is, every few hundred rows rather than every row, and the tool reads that. Every open page reads it every two seconds, so make it one cheap query. A queue may know the numbers already: in Laravel, the batch that Bus::findBatch($id) returns has processedJobs() and totalJobs.
What such a tool has to think of:
- Start it once. A button can be pressed twice, and by two people. Let the start find out that a task is running and write the new one in one statement of the database, not with a read and a write after it.
- Say nothing after the start. The bar on the next page says that the task started. A
success()next to it holds the page for ten seconds, so that it can be read, and the bar stands still that long. After that it is gone with the next run, read or not. What the user has to keep, the number of the task for example, belongs into the page and not into such a message. - A worker can die. Its bar then waits for ever. Let the worker write the time with every step, and say
warning()in place of the bar when that time is too old. - A task can fail. Keep its state next to the numbers, and show
error()in place of the bar with a short message of your own. What the worker threw belongs into your log: it names paths and queries. The export of the demo fails half way when its box "Let the worker give up half way" is ticked before the start. - Stopping is a wish. A button can write down that the task should stop. The worker has to look for that between two steps.
- Whose task it is. The export of the demo belongs to the shop: everybody who opens the page sees the same one. A task that belongs to one user needs that user in its row, and
user()says who is asking. - Who may start it.
allow:says who may open the tool, and whoever opens it can press every button it draws. Where only a few may start or stop a task, askuser()and draw those buttons for them only. - A page that nobody touches pauses after an hour. For a longer task give
refresh()a longerstopAfter:. - Do not let the page do the work, one slice with every refresh. A refresh runs only while somebody has the page open and in view, it waits while they type, and two open tabs would do the same slice twice. The work needs a worker that runs without a browser.
That was the last tutorial. All functions has every function with its parameters, and the examples show ten whole tools.