Browse Source

Add run group quiter.

ZRY 1 year ago
parent
commit
37f6d607af
3 changed files with 60 additions and 0 deletions
  1. 8 0
      .idea/.gitignore
  2. 3 0
      go.mod
  3. 49 0
      run-group-quiter.go

+ 8 - 0
.idea/.gitignore

@@ -0,0 +1,8 @@
+# 默认忽略的文件
+/shelf/
+/workspace.xml
+# 基于编辑器的 HTTP 客户端请求
+/httpRequests/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml

+ 3 - 0
go.mod

@@ -0,0 +1,3 @@
+module git.swzry.com/zry/go-lazy-quiter
+
+go 1.19

+ 49 - 0
run-group-quiter.go

@@ -0,0 +1,49 @@
+package go_lazy_quiter
+
+import (
+	"context"
+	"os"
+	"os/signal"
+)
+
+type RunGroupQuiter struct {
+	qchan chan os.Signal
+	ctx   context.Context
+	cncl  context.CancelFunc
+}
+
+func NewRunGroupQuiter(sig ...os.Signal) *RunGroupQuiter {
+	r := &RunGroupQuiter{qchan: make(chan os.Signal, 0)}
+	if sig == nil {
+		sig = []os.Signal{
+			os.Interrupt,
+			os.Kill,
+		}
+	}
+	signal.Notify(r.qchan, sig...)
+	return r
+}
+
+func (q *RunGroupQuiter) Run() error {
+	q.ctx, q.cncl = context.WithCancel(context.Background())
+	select {
+	case <-q.ctx.Done():
+		{
+			close(q.qchan)
+			return nil
+		}
+	case <-q.qchan:
+		{
+			if q.cncl != nil {
+				q.cncl()
+			}
+			return nil
+		}
+	}
+}
+
+func (q *RunGroupQuiter) Stop(err error) {
+	if q.cncl != nil {
+		q.cncl()
+	}
+}