-
Notifications
You must be signed in to change notification settings - Fork 0
/
stored_job_handler.go
72 lines (60 loc) · 1.81 KB
/
stored_job_handler.go
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
package main
import (
"log"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/robfig/cron/v3"
)
func handleStoredJobs() {
cronner = cron.New()
addTodayJobsToCronner(cronner)
cronner.Start()
// Debugging
log.Print("Starting jobs: ")
for _, entry := range cronner.Entries() {
log.Println(entry)
}
refreshCronner := func() {
log.Println("Old jobs:")
for _, entry := range cronner.Entries() {
// Debugging
log.Println(entry)
if entry.ID != refreshCronEntryID {
cronner.Remove(entry.ID)
}
}
addTodayJobsToCronner(cronner)
log.Println("New jobs: ")
for _, entry := range cronner.Entries() {
log.Println(entry)
}
}
// Daily jobs are loaded at midnight, so that cron does not contain all jobs
refreshCronEntryID, _ = cronner.AddFunc("0 0 * * *", refreshCronner)
}
func addTodayJobsToCronner(cronner *cron.Cron) {
today := time.Now().Weekday()
jobs := storedJobDB.GetJobsByDay(today)
for _, job := range jobs {
// Debugging
log.Println("Job:", job)
log.Println("Cron expression", job.ScheduledTime.ToCronExpression(today))
addJobtoCronner(cronner, job)
}
}
func addJobtoCronner(cronner *cron.Cron, busInfoJob BusInfoJob) {
log.Println("Added", busInfoJob, "job to today's cronner")
cronner.AddFunc(busInfoJob.ScheduledTime.ToCronExpression(time.Now().Weekday()), func() {
fetchAndPushInfo(busInfoJob)
})
}
func fetchAndPushInfo(busJob BusInfoJob) {
log.Println("Fetching information to push")
busArrivalInformation := fetchBusArrivalInformation(busJob.BusStopCode, busJob.BusServiceNo)
textMessage := busArrivalInformation.toMessageString()
sendOutgoingMessage(busJob.ChatID, textMessage)
}
func sendOutgoingMessage(chatID int64, textMessage string) {
messageToSend := tgbotapi.NewMessage(chatID, textMessage)
outgoingMessages <- messageToSend
}