Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
sn01615 committed May 2, 2019
0 parents commit a71aa16
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 0 deletions.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
### 应用场景
1. 限制只开启一个或有限个进程运行

### 局限性
只能在同一台服务器内生效

### Install

```
composer require sn01615/file-lock
```
### Usage

```php
use PhpUtils\FileLock;
FileLock::lock('lockKey');
```
32 changes: 32 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "sn01615/file-lock",
"description": "Php file lock tool.",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "YangLong",
"email": "[email protected]"
}
],
"autoload": {
"psr-4": {
"PhpUtils\\": "src"
}
},
"support": {
"source": "https://github.com/sn01615/file-lock",
"issues": "https://github.com/sn01615/file-lock/issues",
"email": "[email protected]"
},
"keywords": [
"FileLock"
],
"repositories": [
{
"type": "git",
"url": "[email protected]:sn01615/file-lock.git",
"name": "GitHub"
}
]
}
44 changes: 44 additions & 0 deletions src/FileLock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace PhpUtils;

class FileLock
{

private static $fp;

private static $prefix;

private static $instances = [];

private $lockFile;

public static function lock($tag)
{
if (!self::$prefix) {
self::$prefix = sys_get_temp_dir() . '/_PHP_FileLock_';
}

$filename = self::$prefix . sha1($tag);
file_put_contents($filename, time());
self::$fp = fopen($filename, "r+");
if (!flock(self::$fp, LOCK_EX | LOCK_NB)) {
die(0);
}
self::$instances[$tag] = new static();
self::$instances[$tag]->lockFile = $filename;
}

public static function unlock($tag)
{
if (self::$fp !== null) {
flock(self::$fp, LOCK_UN);
}
}

public function __destruct()
{
unlink($this->lockFile);
}
}

0 comments on commit a71aa16

Please sign in to comment.