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
|
package main
import (
"bytes"
"fmt"
"github.com/silvasur/mailremind/confhelper"
"github.com/silvasur/mailremind/model"
"log"
"time"
)
var checkInterval int64
func initCheckjobs() {
checkInterval = confhelper.ConfIntOrFatal(conf, "schedules", "checkInterval")
}
func checkjobs() {
timech := make(chan time.Time)
go func(ch chan time.Time) {
ticker := time.NewTicker(time.Duration(checkInterval) * time.Second)
ch <- time.Now()
for t := range ticker.C {
ch <- t
}
}(timech)
for t := range timech {
checkjobsOnce(t)
}
}
func checkjobsOnce(t time.Time) {
defer func() {
if r := recover(); r != nil {
log.Printf("!! recovered from panic in checkjobsOnce: %s", r)
}
}()
jobs := dbcon.JobsBefore(t)
for _, job := range jobs {
if sendjob(job, t) {
next := job.Schedule().NextAfter(t)
if next.IsZero() {
if err := job.Delete(); err != nil {
log.Printf("Failed deleting job %s after job was done: %s", job.ID(), err)
}
} else {
if err := job.SetNext(next); err != nil {
log.Printf("Failed setting next for job %s: %s", job.ID(), err)
}
}
}
}
}
func sendjob(job model.Job, t time.Time) bool {
user := job.User()
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "From: %s\n", MailFrom)
fmt.Fprintf(buf, "To: %s\n", user.Email())
fmt.Fprintf(buf, "Subject: %s\n", job.Subject())
fmt.Fprintf(buf, "Date: %s\n", t.In(user.Location()).Format(time.RFC1123Z))
fmt.Fprintln(buf, "")
buf.Write(job.Content())
return Mail(user.Email(), MailFrom, buf.Bytes())
}
|