Created
October 10, 2017 05:08
-
-
Save vaskoz/a9116eab4500398cf40654f7d2a6fef0 to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"context" | |
"log" | |
"math/rand" | |
"os" | |
"runtime/trace" | |
"sync" | |
"time" | |
) | |
type Application struct { | |
done chan struct{} | |
} | |
func New() *Application { | |
return &Application{make(chan struct{}, 1)} | |
} | |
func (a *Application) Start(ctx context.Context, wg *sync.WaitGroup) chan struct{} { | |
go func() { | |
select { | |
case <-ctx.Done(): | |
log.Println("Started goroutine received a cancellation order") | |
case <-time.After(15 * time.Minute): | |
log.Println("Yikes") | |
} | |
a.done <- struct{}{} | |
wg.Done() | |
}() | |
return a.done | |
} | |
func main() { | |
rand.Seed(time.Now().UnixNano()) | |
traceFile, err := os.Create("/tmp/aws_spot_main.trace") | |
if err != nil { | |
log.Fatalln("could not create a temp file") | |
} | |
trace.Start(traceFile) | |
defer trace.Stop() | |
ctx, cancel := context.WithCancel(context.Background()) | |
ticker := time.NewTicker(1 * time.Second) | |
app := New() | |
wg := &sync.WaitGroup{} | |
wg.Add(1) | |
done := app.Start(ctx, wg) | |
for { | |
select { | |
case <-done: | |
log.Println("app completed successfully and normally") | |
wg.Wait() | |
log.Println("exiting the main function. All goroutines shutdown") | |
ticker.Stop() | |
return | |
case <-ticker.C: | |
log.Println("checking AWS spot instance termination notice") | |
if rand.Intn(10) == 0 { | |
log.Println("sending cancel message") | |
cancel() | |
} else { | |
log.Println("keep running") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment