Skip to content

Commit 9c9231e

Browse files
committed
Stop the scheduled tasks on disconnect
1 parent fc4a370 commit 9c9231e

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

frameworks/Java/netty/src/main/java/hello/HelloServerHandler.java

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import java.text.SimpleDateFormat;
1111
import java.util.Date;
1212
import java.util.concurrent.ScheduledExecutorService;
13+
import java.util.concurrent.ScheduledFuture;
1314
import java.util.concurrent.TimeUnit;
1415

1516
import com.jsoniter.output.JsonStream;
@@ -34,9 +35,10 @@ protected DateFormat initialValue() {
3435

3536
private HttpHeaders jsonHeaders = makeJsonHeaders(new AsciiString(FORMAT.get().format(new Date())));
3637
private HttpHeaders plaintextHeaders = makePlaintextHeaders(new AsciiString(FORMAT.get().format(new Date())));
38+
private ScheduledFuture<?> refreshHeaders;
3739

3840
public HelloServerHandler(ScheduledExecutorService service) {
39-
service.scheduleWithFixedDelay(new Runnable() {
41+
refreshHeaders = service.scheduleWithFixedDelay(new Runnable() {
4042
private final DateFormat format = FORMAT.get();
4143

4244
@Override
@@ -113,4 +115,13 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
113115
public void channelReadComplete(ChannelHandlerContext ctx) {
114116
ctx.flush();
115117
}
118+
119+
@Override
120+
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
121+
super.channelInactive(ctx);
122+
if (refreshHeaders != null) {
123+
refreshHeaders.cancel(false);
124+
refreshHeaders = null;
125+
}
126+
}
116127
}

0 commit comments

Comments
 (0)