I'm working on a Go microservice where I am using robfig/cron package to schedule jobs, initially thought of using time.Ticker() but package made it easier for me.
My question is how to ensure cron job is registered only once until the running cron completes and prevent multiple goroutines from running simultaneously.
This is different from singleton approach, the block of code inside
RunProcess()must not run until the previous RunProcess function completes.
I am new to golang and its convention. :(
Here is a simplified version of my current implementation:
package main
import (
"fmt"
"sync"
"time"
"github.com/robfig/cron/v3"
)
var isProcessRunning = false
var mu sync.Mutex
func RunProcess() {
mu.Lock()
defer mu.Unlock()
if isProcessRunning {
fmt.Println("Already Running...")
return
}
isProcessRunning = true
fmt.Println("Running...")
// Simulate work
time.Sleep(15 * time.Second)
isProcessRunning = false
}
func InitCron() {
// Create a new cron scheduler
c := cron.New(cron.WithSeconds())
// Add the task to run every 10 seconds
_, err := c.AddFunc("*/10 * * * * *", RunProcess)
if err != nil {
fmt.Println("Error adding cron job:", err)
return
}
// Start the cron scheduler
c.Start()
// Block indefinitely to keep the cron jobs running
select {}
}
func main() {
InitCron()
}
However, I noticed that when InitCron is called multiple times, it can potentially create multiple cron jobs, leading to concurrency issues and unexpected behavior for an lightweight microservice.
Any advice or examples on how to manage this properly would be greatly appreciated.
Running cron in golang and tryin to prevent the cron until it first cron is finished
InitCronrunning multiple times). Note thatRunProcessis probably not doing what you want playground.RunProcessalready ensures this will not run concurrently, so you appear to have already achieved your goal? The code is confusing because "Already Running" will never be printed (due to the lockedMutex); my playground link shows how to address that, but it's unclear if that is what you want. The link ref singleton was in answer to your "noticed that when InitCron is called multiple times..." comment (which seemed to be your main question?).RunProcessexecution usingisProcessRunningvariable, when next cron cycle callsRunProcessit should stop running same code. I am trying to achieve message de-qeueuing in 1st process, the 2nd/3rd process must not affect 1stRunProcessuntil 1st process marked as complete. In your code you have used wg.done() its kind of acknowledgment right?