Skip to content

Instantly share code, notes, and snippets.

@suganoo suganoo/interval.go
Last active Jan 21, 2019

Embed
What would you like to do?
定期実行の理解
package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func doSomething() {
fmt.Println(time.Now())
}
func main() {
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
loop:
for {
select {
case <- sc:
fmt.Println("interrupt")
break loop
//os.Exit(0)
case <-time.After(2 * time.Second):
doSomething()
}
}
}
package main
import (
"context"
"fmt"
"os"
"os/signal"
"time"
)
func doSomething(ctx context.Context, i int) {
//fmt.Println("before")
time.Sleep(5 * time.Second)
//fmt.Println("after")
}
func main() {
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, 3 * time.Second)
defer cancel()
go doSomething(ctx, 1)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
//fmt.Println("sleep start")
//time.Sleep(4*time.Second)
select {
case <-sc:
cancel()
fmt.Println("interrupt")
case <-ctx.Done():
fmt.Println("done:", ctx.Err())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.