Posts

Showing posts from April, 2021

Go goroutine management, WaitGroup and Context

There are two classic way to handle concurrency in go, WaitGroup and Context What is WaitGroup WaitGroup wait for multiple goroutines to finish content_copy func main() { var wg sync.WaitGroup wg.Add(2) go func() { time.Sleep(2*time.Second) fmt.Println("1st task done") wg.Done() }() go func() { time.Sleep(2*time.Second) fmt.Println("2nd task done") wg.Done() }() wg.Wait() fmt.Println("Finish") } The program only finishes when the 2 goroutine finished. Otherwise, it will wait for it. This is useful when we want a program to wait for all tasks to finish. However, sometimes we want to actively cancel a goroutine instead of wait for it to finish. An example can be monitoring. We want to exit monitoring instead of wait for it to finish (it will never finish). We can use channel for this usecase. Channel we can use channel + select to repeatedly checking on a global variable to notify the end of a process content_copy func main() { stop := ...

golang rofig/cron

https://github.com/robfig/cron Cron entries are stored in an array, sorted by their next activation time. Cron sleeps until the next job is due to be run. Upon waking: it runs each entry that is active on that second it calculates the next run times for the jobs that were run it re-sorts the array of entries by next activation time. it goes to sleep until the soonest job. Example content_copy c := cron.New() c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") }) c.AddFunc("@hourly", func() { fmt.Println("Every hour") }) c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") }) c.Start() .. // Funcs are invoked in their own goroutine, asynchronously. ... // Funcs may also be added to a running Cron c.AddFunc("@daily", func() { fmt.Println("Every day") }) .. // Inspect the cron job entries' next and previous run times. inspect(c.Entries()) .. c.Stop() // Stop t...