Last active
November 16, 2023 20:06
-
-
Save aashish-chaubey/45e538959f92d8cc71327d44511cf7f7 to your computer and use it in GitHub Desktop.
Creating goroutines within cron job
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" | |
"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