Skip to content

Commit

Permalink
docs: add comments for status
Browse files Browse the repository at this point in the history
  • Loading branch information
WangYihang committed May 17, 2024
1 parent aaf9d36 commit 5b9966e
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions status.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"time"
)

// Status represents the status of the job.
type Status struct {
Timestamp string `json:"timestamp"`
NumFailed int64 `json:"num_failed"`
Expand All @@ -31,12 +32,22 @@ func newStatusManager() *statusManager {
}
}

func (sm *statusManager) notify() {
status := sm.Snapshot()
for _, ch := range sm.statusChans {
ch <- status
}
}

// Start starts the status manager.
// It will notify all the status channels every second.
func (sm *statusManager) Start() {
for range sm.ticker.C {
sm.notify()
}
}

// Stop stops the status manager.
func (sm *statusManager) Stop() {
sm.notify()
sm.ticker.Stop()
Expand All @@ -45,46 +56,49 @@ func (sm *statusManager) Stop() {
}
}

// IncFailed increments the number of failed jobs.
func (sm *statusManager) IncFailed() {
sm.mutex.Lock()
sm.numFailed++
sm.mutex.Unlock()
}

// IncSucceed increments the number of succeed jobs.
func (sm *statusManager) IncSucceed() {
sm.mutex.Lock()
sm.numSucceed++
sm.mutex.Unlock()
}

// SetTotal sets the total number of jobs.
// It should be called before the job starts.
func (sm *statusManager) SetTotal(total int64) {
sm.mutex.Lock()
sm.numTotal = total
sm.mutex.Unlock()
}

// StatusChan returns a channel that will receive the status of the job.
// The status will be sent every second. It should be called before the job starts.
// You can call it multiple times to get multiple channels.
func (sm *statusManager) StatusChan() <-chan Status {
ch := make(chan Status)
sm.statusChans = append(sm.statusChans, ch)
return ch
}

// Snapshot returns the current status of the job.
func (sm *statusManager) Snapshot() Status {
sm.mutex.Lock()
defer func() func() {
sm.mutex.Lock()
return func() { sm.mutex.Unlock() }
}()()
status := Status{
Timestamp: time.Now().Format(time.RFC3339),
NumFailed: sm.numFailed,
NumSucceed: sm.numSucceed,
NumFinished: sm.numFailed + sm.numSucceed,
NumTotal: sm.numTotal,
}
sm.mutex.Unlock()
return status
}

func (sm *statusManager) notify() {
status := sm.Snapshot()
for _, ch := range sm.statusChans {
ch <- status
}
}

0 comments on commit 5b9966e

Please sign in to comment.