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.
I reused singleton-kinda cron logic from my Java Springboot.
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