cron icon indicating copy to clipboard operation
cron copied to clipboard

can cron get current running jobs or whether any job is running or not

Open lingerle opened this issue 4 years ago • 1 comments

can cron get current running jobs or whether any job is running or not

lingerle avatar Dec 21 '21 12:12 lingerle

package main

import (
	"fmt"
	"github.com/robfig/cron/v3"
	"sync"
	"time"
)

type CronScheduler struct {
	scheduler  *cron.Cron
	jobRunning bool
	mu         sync.Mutex
}

// Constructor for the CronScheduler
func NewCronScheduler() *CronScheduler {
	return &CronScheduler{
		scheduler: cron.New(),
	}
}

// Job function that sets jobRunning flag when the job starts and resets it when it finishes
func (cs *CronScheduler) jobFunction() {
	cs.mu.Lock()
	cs.jobRunning = true
	cs.mu.Unlock()

	// Simulate a long-running job
	fmt.Println("Job started at", time.Now())
	time.Sleep(5 * time.Second) // Simulating job work

	cs.mu.Lock()
	cs.jobRunning = false
	cs.mu.Unlock()

	fmt.Println("Job finished at", time.Now())
}

// Check if any job is currently running
func (cs *CronScheduler) isJobRunning() bool {
	cs.mu.Lock()
	defer cs.mu.Unlock()
	return cs.jobRunning
}

func main() {
	cs := NewCronScheduler()

	// Define a cron job that runs every minute
	spec := "*/1 * * * *" // Every minute

	// Add the job function to the cron scheduler
	_, err := cs.scheduler.AddFunc(spec, cs.jobFunction)
	if err != nil {
		fmt.Println("Error adding job:", err)
		return
	}

	// Start the cron scheduler in the background
	go cs.scheduler.Start()

	// Periodically check if any job is running
	ticker := time.NewTicker(10 * time.Second) // Check every 10 seconds
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			if cs.isJobRunning() {
				fmt.Println("A job is currently running.")
			} else {
				fmt.Println("No job is currently running.")
			}
		}
	}
}

ljluestc avatar Dec 18 '24 16:12 ljluestc