Skip to content

Instantly share code, notes, and snippets.

@suganoo
Last active January 21, 2019 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suganoo/8077611986a6bbbdd4d7adcf79d5e365 to your computer and use it in GitHub Desktop.
Save suganoo/8077611986a6bbbdd4d7adcf79d5e365 to your computer and use it in GitHub Desktop.
定期実行の理解
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