Skip to content

Commit 7dfda17

Browse files
committed
Starting AsyncTask now returns a status object
1 parent 53be8cb commit 7dfda17

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/AsyncTask.php

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Closure;
88
use Illuminate\Process\InvokedProcess;
99
use Illuminate\Support\Facades\Process;
10+
use Illuminate\Support\Str;
1011
use Laravel\SerializableClosure\SerializableClosure;
1112
use LogicException;
1213
use loophp\phposinfo\OsInfo;
@@ -159,10 +160,15 @@ public function run(): void
159160

160161
/**
161162
* Starts this AsyncTask immediately in the background. A runner will then run this AsyncTask.
162-
* @return void
163+
* @return AsyncTaskStatus The status object for the started AsyncTask.
163164
*/
164-
public function start(): void
165+
public function start(): AsyncTaskStatus
165166
{
167+
// prepare the task details
168+
// todo allow changing the task ID
169+
$taskID = null ?? Str::ulid();
170+
$taskStatus = new AsyncTaskStatus($taskID);
171+
166172
// prepare the runner command
167173
$serializedTask = $this->toBase64Serial();
168174
$baseCommand = "php artisan async:run $serializedTask";
@@ -173,7 +179,7 @@ public function start(): void
173179
// but we require cmd (ps won't work here), so might as well force cmd like this
174180
// windows has real max time limit
175181
$this->runnerProcess = Process::quietly()->start("cmd >nul 2>nul /c start /b $baseCommand");
176-
return;
182+
return $taskStatus;
177183
}
178184
// assume anything not windows to be unix
179185
// unix use nohup
@@ -197,6 +203,7 @@ public function start(): void
197203
$timeoutClause = static::$timeoutCmdName . " -s 2 {$this->timeLimit}";
198204
}
199205
$this->runnerProcess = Process::quietly()->start("nohup $timeoutClause $baseCommand >/dev/null 2>&1");
206+
return $taskStatus;
200207
}
201208

202209
/**

src/AsyncTaskStatus.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@
1313
*/
1414
class AsyncTaskStatus
1515
{
16+
/**
17+
* The cached task ID for quick ID reusing. We will most probably reuse this ID many times.
18+
* @var string|null
19+
*/
20+
private string|null $encodedTaskID = null;
21+
1622
/**
1723
* Constructs a status object.
1824
* @param string $taskID The task ID of the async task so to check its status.
@@ -25,4 +31,16 @@ public function __construct(
2531
throw new RuntimeException("AsyncTask IDs cannot be blank");
2632
}
2733
}
34+
35+
/**
36+
* Returns the task ID encoded in base64, mainly for result checking.
37+
* @return string The encoded task ID.
38+
*/
39+
public function getEncodedTaskID(): string
40+
{
41+
if ($this->encodedTaskID === null) {
42+
$this->encodedTaskID = base64_encode($this->taskID);
43+
}
44+
return $this->encodedTaskID;
45+
}
2846
}

0 commit comments

Comments
 (0)