Skip to content

Commit dbae52c

Browse files
Timer pattern
1 parent 903bb5c commit dbae52c

1 file changed

Lines changed: 105 additions & 0 deletions

File tree

‎chapter6/patterns/timer/timer.go‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// Copyright Information.
2+
//
3+
// This sample program demonstrations how to use a timer channel and hook
4+
// into the OS using a channel to receive OS events.
5+
package main
6+
7+
import (
8+
"fmt"
9+
"log"
10+
"os"
11+
"os/signal"
12+
"sync/atomic"
13+
"time"
14+
)
15+
16+
// Give the program 10 seconds to complete the work.
17+
const timeoutSeconds = 10 * time.Second
18+
19+
// Flag to indicate to running goroutines to shut
20+
// down the program immediately.
21+
var shutdown int32 = 0
22+
23+
func main() {
24+
log.Println("Starting Process")
25+
26+
// Create a channel to talk with the OS.
27+
sigChan := make(chan os.Signal, 1)
28+
signal.Notify(sigChan, os.Interrupt)
29+
30+
// Set the timeout channel.
31+
timeout := time.After(timeoutSeconds)
32+
33+
// Launch the process.
34+
log.Println("Launching Processor")
35+
complete := make(chan error)
36+
go processor(complete)
37+
38+
ControlLoop:
39+
for {
40+
select {
41+
case <-sigChan:
42+
log.Println("OS INTERRUPT - Shutting Down Early")
43+
44+
// Set the flag to indicate the program should be shutdown early.
45+
// Try to shutdown cleanly.
46+
atomic.StoreInt32(&shutdown, 1)
47+
continue
48+
49+
case <-timeout:
50+
log.Println("Timeout - Killing Program")
51+
52+
// We have taken too much time. Kill the app hard.
53+
log.Println("Process Ended")
54+
os.Exit(1)
55+
56+
case err := <-complete:
57+
log.Printf("Task Complete: Error[%s]", err)
58+
break ControlLoop
59+
}
60+
}
61+
62+
// Program finished.
63+
log.Println("Process Ended")
64+
return
65+
}
66+
67+
// isShutdown returns the value of the shutdown flag.
68+
func isShutdown() bool {
69+
value := atomic.LoadInt32(&shutdown)
70+
if value == 1 {
71+
return true
72+
}
73+
74+
return false
75+
}
76+
77+
// processor instantiates the specified inventory processor and runs the job.
78+
func processor(complete chan<- error) {
79+
log.Println("Processor - Starting")
80+
81+
// Message returned through the complete channel.
82+
var err error
83+
84+
// Schedule this anonymous function to be executed when
85+
// the function returns.
86+
defer func() {
87+
log.Println("Processor - Completed")
88+
89+
// Signal the goroutine is shutdown.
90+
complete <- err
91+
}()
92+
93+
// Simulate some iterative work.
94+
for {
95+
log.Println("Processor - Doing Work")
96+
time.Sleep(5 * time.Second)
97+
98+
// Check if we are being asked to shutdown before we
99+
// complete our work.
100+
if isShutdown() {
101+
err = fmt.Errorf("Processor - Shutting Down")
102+
return
103+
}
104+
}
105+
}

0 commit comments

Comments
 (0)