Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions crontab.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,20 @@ import (
"time"
)

// StatsFunc func representing custom execution statistics
type StatsFunc func() interface{}

// ExecStats struct representing a standardized wrapper for execution statistics
type ExecStats struct {
JobType string
Stats StatsFunc
}

// Crontab struct representing cron table
type Crontab struct {
ticker *time.Ticker
jobs []job
ticker *time.Ticker
jobs []job
statsChan chan ExecStats
}

// job in cron table
Expand Down Expand Up @@ -46,7 +56,8 @@ func New() *Crontab {
// new creates new crontab, arg provided for testing purpose
func new(t time.Duration) *Crontab {
c := &Crontab{
ticker: time.NewTicker(t),
ticker: time.NewTicker(t),
statsChan: make(chan ExecStats),
}

go func() {
Expand All @@ -58,6 +69,11 @@ func new(t time.Duration) *Crontab {
return c
}

// StatsChan returns the channel to consume execution statistics
func (c *Crontab) StatsChan() chan ExecStats {
return c.statsChan
}

// AddJob to cron table
//
// Returns error if:
Expand Down
49 changes: 49 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package crontab_test
import (
"fmt"
"log"
"testing"
"time"

"github.com/mileusna/crontab"
)
Expand Down Expand Up @@ -38,3 +40,50 @@ func myFunc3() {
func myFunc2(s string, n int) {
fmt.Printf("We have params here, string `%s` and nymber %d\n", s, n)
}

// go test -v ./... -run TestExampleExecStats
func TestExampleExecStats(t *testing.T) {
ctab := crontab.New()

ctab.MustAddJob("* * * * *", myFuncWithStats, ctab.StatsChan())
log.Println("Waiting a bit for the test to complete...")

for i := 1; i <= 1; i++ {
myExecStats := <-ctab.StatsChan()
if myExecStats.JobType != "myFuncWithStats" {
t.Errorf("Found an unexpected Job type")
}
customStuff := myExecStats.Stats().(*myCustomStats)
if customStuff.strParam != "foo" {
t.Errorf("Found an unexpected string parameter in the stats")
}
if customStuff.intParam != 42 {
t.Errorf("Found an unexpected integer parameter in the stats")
}
ctab.Shutdown()
log.Println("Done with the test, the received stats:", customStuff)
}
}

// custom execution stats depending on the scheduled function
type myCustomStats struct {
strParam string
intParam int
}

func myFuncWithStats(statsChan chan crontab.ExecStats) {
// work a bit...
time.Sleep(1 * time.Second)
// publish the execution stats...
statsChan <- crontab.ExecStats{
// ID to identify the job
JobType: "myFuncWithStats",
// custom execution stats
Stats: func() interface{} {
return &myCustomStats{
strParam: "foo",
intParam: 42,
}
},
}
}