-
Notifications
You must be signed in to change notification settings - Fork 0
/
cron.go
executable file
·76 lines (67 loc) · 1.71 KB
/
cron.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
73
74
75
76
package service
import (
"fmt"
"github.com/ankogit/wwc_social_rating/pkg/models"
"github.com/ankogit/wwc_social_rating/pkg/storage"
"github.com/ankogit/wwc_social_rating/pkg/telegram/jobs"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/robfig/cron/v3"
)
type CronService struct {
Scheduler *cron.Cron
ChatRepository storage.ChatRepository
TelegramNotifications *jobs.TelegramNotifications
}
func NewCronService(sh *cron.Cron, r storage.ChatRepository, tn *jobs.TelegramNotifications) *CronService {
return &CronService{
Scheduler: sh,
ChatRepository: r,
TelegramNotifications: tn,
}
}
func (c *CronService) Start() {
c.Scheduler.Start()
}
func (c *CronService) Init() {
chats, err := c.ChatRepository.All()
if err != nil {
fmt.Println(err)
}
for _, chat := range chats {
if chat.EntryId != 0 && chat.NotificationCron != "" {
jobID, err := c.Scheduler.AddFunc(chat.NotificationCron, func() {
c.TelegramNotifications.NotifyStats(&tgbotapi.Message{
Chat: &tgbotapi.Chat{
ID: chat.ID,
},
})
})
if err != nil {
fmt.Println(err)
}
chat.EntryId = jobID
if err := c.ChatRepository.Save(chat); err != nil {
fmt.Println(err)
}
}
}
}
func (c *CronService) SetJob(chat *models.Chat, notificationCron string) (cron.EntryID, error) {
c.RemoveJob(chat)
jobID, err := c.Scheduler.AddFunc(chat.NotificationCron, func() {
c.TelegramNotifications.NotifyStats(&tgbotapi.Message{
Chat: &tgbotapi.Chat{
ID: chat.ID,
},
})
})
if err != nil {
return 0, err
}
return jobID, nil
}
func (c *CronService) RemoveJob(chat *models.Chat) {
if chat.EntryId != 0 {
c.Scheduler.Remove(chat.EntryId)
}
}