Skip to content

Commit ad410a8

Browse files
committed
document withHeartbeat
1 parent 43bbd49 commit ad410a8

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

collections.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4328,3 +4328,29 @@ $users->take(5)->all();
43284328
// The rest are hydrated from the database...
43294329
$users->take(20)->all();
43304330
```
4331+
4332+
<a name="method-with-heartbeat"></a>
4333+
#### `withHeartbeat()` {.collection-method}
4334+
4335+
The `withHeartbeat` method allows you to execute a callback at regular time intervals while a lazy collection is being enumerated. This is particularly useful for long-running operations that require periodic maintenance tasks, such as extending locks or sending progress updates:
4336+
4337+
```php
4338+
use Carbon\CarbonInterval;
4339+
use Illuminate\Support\Facades\Cache;
4340+
4341+
$lock = Cache::lock('generate-reports', CarbonInterval::minutes(5));
4342+
4343+
if ($lock->get()) {
4344+
try {
4345+
Report::where('status', 'pending')
4346+
->lazy()
4347+
->withHeartbeat(
4348+
CarbonInterval::minutes(4),
4349+
fn () => $lock->extend(CarbonInterval::minutes(5))
4350+
)
4351+
->each($report->process(...));
4352+
} finally {
4353+
$lock->release();
4354+
}
4355+
}
4356+
```

0 commit comments

Comments
 (0)