-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
83 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# Graceful Shutdown | ||
|
||
通常應用程式在接受到 `kill -9` `kill -15` 等等相關訊號會直接關閉,但是實際上可以透過程式去處理取得這些 `signal` 時,要怎麼安全地關閉應用程式。 | ||
|
||
|
||
參考 [Graceful Shutdown Example Code](./main.go) | ||
|
||
在範例程式中,可以試著換成 `newNormalContext`,並且在印出 0 的時候去中斷程式,會看到使用 `newNormalContext` 時並不會看到 1 被印出來,就意外的被中斷。 | ||
|
||
但是當使用 `newGracefulContext` 接收 signal 的情況下,可以做一些後續收尾的動作。所以用這個 `newGracefulContext` 看到 0 的時候去中斷程式,會看到 1 被印出來。 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
package main | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"os" | ||
"os/signal" | ||
"sync" | ||
"time" | ||
) | ||
|
||
func newNormalContext() context.Context { | ||
return context.Background() | ||
} | ||
|
||
func newGracefulContext() context.Context { | ||
ctx, cancel := context.WithCancel(context.Background()) | ||
|
||
go func() { | ||
sig := make(chan os.Signal) | ||
signal.Notify(sig) // accept all signal | ||
defer signal.Stop(sig) | ||
|
||
select { | ||
case <-ctx.Done(): | ||
case <-sig: | ||
cancel() | ||
} | ||
|
||
fmt.Println("graceful shutdown") | ||
}() | ||
|
||
return ctx | ||
} | ||
|
||
func main() { | ||
wg := sync.WaitGroup{} | ||
wg.Add(1) | ||
|
||
ctx := newGracefulContext() | ||
//ctx := newNormalContext() | ||
go func(ctx context.Context) { | ||
defer wg.Done() | ||
|
||
data := 0 | ||
fmt.Println(data) | ||
|
||
// simulate the hard work, then set data of 1 | ||
time.Sleep(2 * time.Second) | ||
data = 1 | ||
fmt.Println(data) | ||
|
||
select { | ||
case <-ctx.Done(): | ||
fmt.Println("skip following job") | ||
return | ||
default: | ||
} | ||
|
||
time.Sleep(2 * time.Second) | ||
data = 2 | ||
fmt.Println(data) | ||
}(ctx) | ||
|
||
wg.Wait() | ||
} |