Golang and its concurrency & parallel ecosystem ? How to do

My use case when using thread in Java were :
a cron is reading a specific table in the database for specifique cron expression
an event is triggered by the cron
the thread begin theses operations for multiples users (2000)
Foreach user

  • Step a : call external api for financial rule
  • Step b : if a ok proceed to call an another external api with the given result from a)
  • if Step b
  1. do compute operation
  2. send sms
  3. populate into the table
    Nota Bene :
    When exception occurs in all these steps, a step of logging the errors in a table is used and the steps never stop until reach all the 2000 users.

How to do this in Golang ecosystem with concurrency & parallel ?
An useful sample according to my pseudo-code will be helpful .
Thanks

I don’t fully understand your requirements, but “doing some task every x seconds on a goroutine without blocking your main app” is relatively simple. Something like this should get you started:

// Context for our goroutine
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Mutext to protect our long running job and make sure 
// it doesn't run concurrently
mu := sync.Mutex{}

// Spin up goroutine to run our job every 10 seconds
// Obviously adjust timer as needed.
go func() {
	t := time.NewTicker(10 * time.Second)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return // exit goroutine
		case <-t.C:
			mu.Lock()
			doLongRunningJobWithoutBlockingApp()
			mu.Unlock()
		}
	}
}()

You could also take a look at cron-based libraries such as robfig/cron. I’ve used that for tasks such as nightly report generation and batch email handling (notifications of pending account expirations, etc.) and it works fine.

Thanks you for your reply. I have updated my requirements if it is clear it will be precious for me your helps.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.