summaryrefslogtreecommitdiff
path: root/jobs.go
blob: 02683c8a3bde636cdc39b8bb448365b597aebd03 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main

import "time"

type Job interface {
	Schedule()
	Stop()
	Run()
}

type jobIdentifier int

const (
	JobIdCloseDecisions jobIdentifier = iota
)

var rescheduleChannel = make(chan jobIdentifier, 1)

func JobScheduler(quitChannel chan int) {
	var jobs = map[jobIdentifier]Job{
		JobIdCloseDecisions: NewCloseDecisionsJob(),
	}
	logger.Println("INFO started job scheduler")

	for {
		select {
		case jobId := <-rescheduleChannel:
			job := jobs[jobId]
			logger.Println("INFO reschedule job", job)
			job.Schedule()
		case <-quitChannel:
			for _, job := range jobs {
				job.Stop()
			}
			logger.Println("INFO stop job scheduler")
			return
		}
	}
}

type CloseDecisionsJob struct {
	timer *time.Timer
}

func NewCloseDecisionsJob() *CloseDecisionsJob {
	job := &CloseDecisionsJob{}
	job.Schedule()
	return job
}

func (j *CloseDecisionsJob) Schedule() {
	var nextDue *time.Time
	nextDue, err := GetNextPendingDecisionDue()
	if err != nil {
		logger.Fatal("ERROR Could not get next pending due date")
		if j.timer != nil {
			j.timer.Stop()
			j.timer = nil
		}
		return
	}
	if nextDue == nil {
		if j.timer != nil {
			j.timer.Stop()
			j.timer = nil
		}
	} else {
		logger.Println("INFO scheduling CloseDecisionsJob for", nextDue)
		when := nextDue.Sub(time.Now())
		if j.timer != nil {
			j.timer.Reset(when)
		} else {
			j.timer = time.AfterFunc(when, j.Run)
		}
	}
}

func (j *CloseDecisionsJob) Stop() {
	if j.timer != nil {
		j.timer.Stop()
	}
}

func (j *CloseDecisionsJob) Run() {
	logger.Println("INFO running CloseDecisionsJob")
	err := CloseDecisions()
	if err != nil {
		logger.Println("ERROR closing decisions", err)
	}
	rescheduleChannel <- JobIdCloseDecisions
}

func (j *CloseDecisionsJob) String() string {
	return "CloseDecisionsJob"
}