-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTask.php
105 lines (90 loc) · 2.39 KB
/
Task.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
/**
* DframeFramework
* Copyright (c) Sławomir Kaleta
*
* @license https://github.com/dframe/dframe/blob/master/LICENCE (MIT)
*/
namespace Dframe\Cron;
use Dframe\Cron\Exceptions\TaskException;
use Dframe\Loader\Loader;
use Exception;
use InvalidArgumentException;
/**
* Config Class
*
* @author Sławomir Kaleta <[email protected]>
*/
abstract class Task extends Loader
{
/**
* @param $key
* @param $callback
* @param array $bind
* @param int $ttl
*
* @return array
* @throws Exception
*/
protected function inLock($key, $callback, array $bind = [], $ttl = 3600): array
{
if (!defined('APP_DIR')) {
throw new TaskException('Please Define APP_DIR in Main config.php', 500);
}
$dir = self::LOG_DIR;
$file = $key . '.txt';
$this->checkDir($dir);
$dirLog = $dir . $file;
if (!is_callable($callback)) {
throw new InvalidArgumentException();
}
$fp = fopen($dirLog, "w");
if (flock($fp, LOCK_EX | LOCK_NB)) { // do an exclusive lock
$data = call_user_func_array($callback, $bind);
flock($fp, LOCK_UN); // release the lock
$this->lockTime($key, $ttl);
} else {
return ['return' => false];
}
fwrite($fp, date("d-m-Y H:i:s"));
fclose($fp);
return ['return' => true, 'response' => $data];
}
/**
* @param $path
*
* @throws Exception
*/
protected function checkDir($path): void
{
if (!is_dir($path)) {
if (!mkdir($path, 0777, true)) {
throw new Exception('Unable to create' . $path, '', 403);
}
}
}
/**
* @param $key
* @param int $ttl
*
* @return bool
* @throws Exception
*/
protected function lockTime($key, $ttl = 59): bool
{
if (!defined('APP_DIR')) {
throw new TaskException('Please Define APP_DIR in Main config.php', 500);
}
$dir = $dirLog = self::LOG_DIR;
$file = $key . '.txt';
$this->checkDir($dir);
$dirLog = $dir . $file;
if (file_exists($dirLog) and filemtime($dirLog) + $ttl > time()) {
return false;
}
$fp = fopen($dirLog, "w");
fwrite($fp, date("d-m-Y H:i:s"));
fclose($fp);
return true;
}
}