You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Utilize Laravel Processes to run PHP code asynchronously.
8
+
Utilize Laravel Processes to run PHP code asynchronously, as if using Laravel Concurrency.
9
9
10
10
## What really is this?
11
11
[Laravel Processes](https://laravel.com/docs/10.x/processes) was first introduced in Laravel 10. This library wraps around `Process::start()` to let you execute code in the background to achieve async, albeit with some caveats:
@@ -45,7 +45,7 @@ If you are on Unix, check that you also have the following:
45
45
## Change log
46
46
Please see `CHANGELOG.md`.
47
47
48
-
## Example code
48
+
## Example code and features
49
49
Tasks can be defined as PHP closures, or (recommended) as an instance of a class that implements `AsyncTaskInterface`.
50
50
51
51
A very simple example task to write Hello World to a file:
@@ -54,10 +54,7 @@ A very simple example task to write Hello World to a file:
54
54
// define the task...
55
55
$target = "document.txt";
56
56
$task = new AsyncTask(function () use ($target) {
57
-
$fp = fopen($target, "w");
58
-
fwrite($fp, "Hello World!!");
59
-
fflush($fp);
60
-
fclose($fp);
57
+
file_put_contents($target, "Hello World!");
61
58
});
62
59
63
60
// if you are using interfaces, then it is just like this:
- Don't sleep too long! On Windows, timeout handlers cannot trigger while your task is sleeping.
89
+
- Use short but frequent sleeps instead.
90
+
- Avoid using `SIGINT`! On Unix, this signal is reserved for timeout detection.
91
+
92
+
### Task IDs
93
+
You can assign task IDs to tasks before they are run, but you cannot change them after the tasks are started. This allows you to track the statuses of long-running tasks across web requests.
94
+
95
+
By default, if a task does not has its user-specified task ID when starting, a ULID will be generated as its task ID.
96
+
97
+
```php
98
+
// create a task with a specified task ID...
99
+
$task = new AsyncTask(function () {}, "customTaskID");
100
+
101
+
// will return a status object for immediate checking...
102
+
$status = $task->start();
103
+
104
+
// in case the task ID was not given, what is the generated task ID?
105
+
$taskID = $status->taskID;
106
+
107
+
// is that task still running?
108
+
$status->isRunning();
109
+
110
+
// when task IDs are known, task status objects can be recreated on-the-fly
111
+
$anotherStatus = new AsyncTaskStatus("customTaskID");
112
+
```
113
+
114
+
Some tips:
115
+
- Task IDs can be optional (i.e. `null`) but CANNOT be blank (i.e. `""`)!
116
+
- If multiple tasks are started with the same task ID, then the task status object will only track the first task that was started
117
+
- Known issue: on Windows, checking task statuses can be slow (about 0.5 - 1 seconds) due to underlying bottlenecks
0 commit comments