Created
April 16, 2018 09:10
-
-
Save burubur/b7a238458972331affb76ca1d0cc820d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
| "encoding/json" | |
| "fmt" | |
| "log" | |
| "time" | |
| ) | |
| // Movie doc | |
| type Movie struct { | |
| Title string | |
| Year int `json:"released"` | |
| Color bool `json:"color,omitempty"` | |
| Actors []string | |
| } | |
| func main() { | |
| jsonMarshall() | |
| intervalTimer() | |
| tickTimer() | |
| timerAndTicker() | |
| } | |
| func jsonMarshall() { | |
| var movies = Movie{ | |
| Title: "Casablanca", Year: 1992, Color: false, Actors: []string{"Humprey", "Mubarok"}, | |
| } | |
| data, err := json.MarshalIndent(movies, "", " ") | |
| if err != nil { | |
| log.Fatalf("%s", err) | |
| } | |
| fmt.Printf("\n%s\n", data) | |
| } | |
| func intervalTimer() { | |
| timer := time.NewTimer(time.Second * 2) | |
| defer fmt.Printf("The End\n") | |
| fmt.Printf("Starting...\n") | |
| fmt.Printf("Counting...\n") | |
| <-timer.C | |
| println("Wohoo") | |
| } | |
| func tickTimer() { | |
| ticker := time.NewTicker(time.Second) | |
| go func() { | |
| for t := range ticker.C { | |
| fmt.Println("Tick at", t) | |
| } | |
| }() | |
| time.Sleep(time.Second * 10) | |
| ticker.Stop() | |
| fmt.Println("Stopped") | |
| } | |
| func timerAndTicker() { | |
| timeChannel := time.NewTimer(time.Second * 5).C | |
| tickChannel := time.NewTicker(time.Second).C | |
| doneChannel := make(chan bool) | |
| go func() { | |
| time.Sleep(time.Second * 10) | |
| doneChannel <- true | |
| }() | |
| for { | |
| select { | |
| case <-timeChannel: | |
| fmt.Println("timer is expired") | |
| case <-tickChannel: | |
| fmt.Println("ticker is ticked") | |
| case <-doneChannel: | |
| fmt.Println("Done") | |
| return | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment