Skip to content

Instantly share code, notes, and snippets.

@aashish-chaubey
Last active November 16, 2023 20:06
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 aashish-chaubey/45e538959f92d8cc71327d44511cf7f7 to your computer and use it in GitHub Desktop.
Save aashish-chaubey/45e538959f92d8cc71327d44511cf7f7 to your computer and use it in GitHub Desktop.
Creating goroutines within cron job
package main
import (
"fmt"
"http://github.com/robfig/cron/v3"
"sync"
"time"
)
func one() {
fmt.Println("One")
return
}
func two() {
fmt.Println("Two")
return
}
func three() {
time.Sleep(5 * time.Second)
fmt.Println("Three")
return
}
func secondary_func(done chan bool) {
defer close(done)
one()
two()
three()
}
func main() {
c := cron.New()
_, err := c.AddFunc("*/2 * * * *", func() {
users := []string{"user1", "user2", "user3"}
var wg sync.WaitGroup
for i := 0; i < len(users); i++ {
wg.Add(1)
go func(user string) {
defer wg.Done()
fmt.Println(user)
done := make(chan bool)
go secondary_func(done)
select {
case <-done:
case <-time.After(2 * time.Second):
fmt.Println("Goroutine timed out")
}
}(users[i])
}
wg.Wait()
})
if err != nil {
fmt.Println("Error adding cron job:", err)
return
}
start()
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment