Last active
January 21, 2019 10:16
-
-
Save suganoo/8077611986a6bbbdd4d7adcf79d5e365 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 ( | |
"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() | |
} | |
} | |
} |
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" | |
"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