我有以下的(簡單)鎖定爲Laravel 5.3命令代碼:清理控制檯命令
private $hash = null;
public final function handle() {
try {
$this->hash = md5(serialize([ static::class, $this->arguments(), $this->options() ]));
$this->info("Generated signature ".$this->hash,"v");
if (Redis::exists($this->hash)) {
$this->hash = null;
throw new \Exception("Method ".$this->signature." is already running");
}
Redis::set($this->hash, true);
$this->info("Running method","vv");
$this->runMutuallyExclusiveCommand(); //Actual command is not important here
$this->cleanup();
} catch (\Exception $e) {
$this->error($e->getMessage());
}
}
public function cleanup() {
if (is_string($this->hash)) {
Redis::del($this->hash);
}
}
指令是否允許通過其執行週期通常也能正常工作(包括處理時有一個PHP例外)。然而,當通過其他方式(例如,CTRL-C或終端窗口關閉)中斷命令時會出現問題。在這種情況下,清理代碼不會運行,並且該命令被認爲仍然是「正在執行」,所以我需要手動從緩存中刪除條目以重新啓動它。我試圖運行在__destruct
功能cleanup
代碼,但似乎並沒有被任何調用。
我的問題是,有沒有設置一些代碼的方式當命令終止它不管如何終止跑出?
我不認爲一個cron是合適的,因爲我不知道該緩存條目是否存在因爲任務被殺害或因爲任務仍在運行。但我願意承認答案確實不是。 – apokryfos