Skip to content

Commit 320942f

Browse files
authored
Merge pull request #19 from felixlehmann/sighup-handling
Add SIGHUP handling for graceful exit of worker
2 parents 1cf4b58 + 118d4b4 commit 320942f

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,3 +161,9 @@ messages are received from a set of queues in CakeSQS. This is an example
161161
The functions registered to handle jobs will receive the message body from the queue after decoding it using `json_decode`.
162162

163163
IMPORTANT: return true to delete the message upon processing, false to leave the message in the queue and re - process later
164+
165+
## Kill worker softly with SIGHUP
166+
167+
To kill a long lived worker shell in the middle of the iterations loop, you can send SIGHUP by calling `kill -1 PID` on the commandline (PID is the process Id of your running worker shell).
168+
169+
This will cause the current iteration to finish and stop the worker afterwards.

src/Shell/Task/QueueWorkerTask.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,13 @@ class QueueWorkerTask extends Shell
3434
*/
3535
protected $callbacks = [];
3636

37+
/**
38+
* Exit signal
39+
*
40+
* @var bool
41+
*/
42+
private $exit = false;
43+
3744
/**
3845
* Read the queue and process messages, this work process will block for a number of
3946
* iterations, so can set this work process to last forever setting the $iterations param
@@ -48,6 +55,13 @@ class QueueWorkerTask extends Shell
4855
public function work($name = 'default', $iterations = self::MAX_MESSAGES_PROCESSED)
4956
{
5057
$this->log(sprintf("Starting %s worker", $name), 'info', 'sqs');
58+
59+
if (function_exists('pcntl_signal')) {
60+
pcntl_signal(SIGHUP, function () {
61+
$this->exit = true;
62+
});
63+
}
64+
5165
$simpleQueue = $this->getSimpleQueue();
5266
$i = 0;
5367
$infinite_loop = ($iterations == -1);
@@ -69,6 +83,15 @@ public function work($name = 'default', $iterations = self::MAX_MESSAGES_PROCESS
6983
if ($iterations > -1) {
7084
$i++;
7185
}
86+
87+
if (function_exists('pcntl_signal_dispatch')) {
88+
pcntl_signal_dispatch();
89+
}
90+
91+
if ($this->exit == true) {
92+
$this->log(sprintf("SIGHUP Received in iteration %d of %d", $i, $iterations), 'info', 'sqs');
93+
break 1;
94+
}
7295
}
7396
$this->log(sprintf("Finished %s worker", $name), 'info', 'sqs');
7497
}

0 commit comments

Comments
 (0)