1
+ <?php
2
+ namespace PHPQueue ;
3
+
4
+ use Clio \Console ;
5
+ use Clio \Daemon as D ;
6
+
7
+ abstract class Daemon
8
+ {
9
+ public $ queue_name = null ;
10
+ public $ pid_file ;
11
+ public $ log_root ;
12
+ public $ stdout = '/tmp/stdout.log ' ;
13
+ public $ stderr = '/tmp/stderr.log ' ;
14
+
15
+ /**
16
+ * @param string $pid_file
17
+ * @param string $log_root
18
+ */
19
+ public function __construct ($ pid_file , $ log_root )
20
+ {
21
+ $ this ->pid_file = $ pid_file ;
22
+ $ this ->log_root = $ log_root ;
23
+ }
24
+
25
+ public function run ()
26
+ {
27
+ global $ argv ;
28
+ if (empty ($ argv [1 ]))
29
+ {
30
+ Console::output ("Unknown action. " );
31
+ die ();
32
+ }
33
+ if (empty ($ this ->queue_name ))
34
+ {
35
+ Console::output ("Queue is not set. " );
36
+ die ();
37
+ }
38
+ switch ($ argv [1 ])
39
+ {
40
+ case 'start ' :
41
+ $ this ->start ();
42
+ break ;
43
+ case 'stop ' :
44
+ $ this ->stop ();
45
+ break ;
46
+ case 'restart ' :
47
+ $ this ->restart ();
48
+ break ;
49
+ default :
50
+ Console::output ("Unknown action. " );
51
+ break ;
52
+ }
53
+ }
54
+
55
+ protected function start ()
56
+ {
57
+ Console::stdout ('Starting... ' );
58
+ try
59
+ {
60
+ if (D::isRunning ($ this ->pid_file )) {
61
+ Console::output ('%y[Already Running]%n ' );
62
+ } else {
63
+ $ queue = $ this ->queue_name ;
64
+ $ log_path = $ this ->log_root ;
65
+ D::work (array (
66
+ 'pid ' => $ this ->pid_file
67
+ , 'stdout ' => $ this ->stdout
68
+ , 'stderr ' => $ this ->stderr
69
+ ),
70
+ function ($ stdin , $ stdout , $ sterr ) use ($ queue , $ log_path )
71
+ {
72
+ $ runner = new Runner ($ queue , array ('logPath ' =>$ log_path ));
73
+ $ runner ->run ();
74
+ }
75
+ );
76
+ Console::output ('%g[OK]%n ' );
77
+ }
78
+ }
79
+ catch (\Exception $ ex )
80
+ {
81
+ Console::output ('%r[FAILED]%n ' );
82
+ }
83
+ }
84
+
85
+ protected function stop ()
86
+ {
87
+ Console::stdout ('Stopping... ' );
88
+ try
89
+ {
90
+ if (!D::isRunning ($ this ->pid_file )) {
91
+ Console::output ('%y[Daemon not running]%n ' );
92
+ } else {
93
+ D::kill ($ this ->pid_file , true );
94
+ Console::output ('%g[OK]%n ' );
95
+ }
96
+ }
97
+ catch (\Exception $ ex )
98
+ {
99
+ Console::output ('%r[FAILED]%n ' );
100
+ }
101
+ }
102
+
103
+ protected function restart ()
104
+ {
105
+ $ this ->stop ();
106
+ $ this ->start ();
107
+ }
108
+ }
0 commit comments