1: <?php
2:
3: namespace Charcoal\App\Script;
4:
5: use \Exception;
6:
7: 8: 9:
10: trait CronScriptTrait
11: {
12: 13: 14:
15: private $useLock = false;
16:
17: 18: 19: 20:
21: private $lockFilePointer;
22:
23: 24: 25: 26:
27: public function setUseLock($useLock)
28: {
29: $this->useLock = !!$useLock;
30: return $this;
31: }
32:
33: 34: 35:
36: public function useLock()
37: {
38: return $this->useLock;
39: }
40:
41: 42: 43: 44:
45: public function startLock()
46: {
47: $lockName = str_replace('\\', '-', get_class($this));
48: $lockName .= md5(__DIR__);
49:
50: $lockFile = sys_get_temp_dir().'/'.$lockName;
51: $this->lockFilePointer = fopen($lockFile, 'w');
52: if (!$this->lockFilePointer) {
53: throw new Exception(
54: sprintf('Can not run action. Lock file not available: "%s"', $lockFile)
55: );
56: }
57: if (flock($this->lockFilePointer, LOCK_EX)) {
58: return true;
59: } else {
60: throw new Exception(
61: sprintf('Can not run action. Action locked: "%s".', $lockFile)
62: );
63: }
64: }
65:
66: 67: 68:
69: public function stopLock()
70: {
71: if ($this->lockFilePointer) {
72: flock($this->lockFilePointer, LOCK_UN);
73: fclose($this->lockFilePointer);
74: }
75: }
76: }
77: