-
Notifications
You must be signed in to change notification settings - Fork 1
/
cron.go
88 lines (74 loc) · 1.75 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
77
78
79
80
81
82
83
84
85
86
87
88
package cronjob
import (
"errors"
"fmt"
"github.com/robfig/cron/v3"
"github.com/the-go-dragons/final-project2/internal/domain"
"github.com/the-go-dragons/final-project2/internal/usecase"
"github.com/the-go-dragons/final-project2/pkg/rabbitmq"
)
var CronJobRunner *cron.Cron
func NewCronJobRunner() {
if CronJobRunner == nil {
CronJobRunner = cron.New()
CronJobRunner.Start()
}
fmt.Println("Cron runner started")
}
type JobWithRepetitions struct {
EntryID cron.EntryID
Job cron.Job
Repetitions uint
Counter uint
StopOnFinish bool
}
func (j *JobWithRepetitions) Run() {
j.Counter++
j.Job.Run()
if j.StopOnFinish && j.Counter >= j.Repetitions {
CronJobRunner.Remove(j.EntryID)
}
}
func AddNewJob(
user domain.User,
period string,
massage string,
senderNumber string,
receiverNumbers string,
repetitionCount uint,
smsS usecase.SMSService,
) (int, error) {
if CronJobRunner == nil {
NewCronJobRunner()
}
if repetitionCount <= 0 {
return 0, errors.New("not enough repetition count")
}
parsedSchedule, err := cron.ParseStandard(period)
if err != nil {
return 0, err
}
job := &JobWithRepetitions{
Job: cron.FuncJob(func() { // Wrap the actual job function
rabbitmq.NewMassage(rabbitmq.SMSBody{
Sender: senderNumber,
Receivers: receiverNumbers,
Massage: massage,
})
smsHistoryRecord := domain.SMSHistory{
UserId: user.ID,
User: user,
SenderNumber: senderNumber,
ReceiverNumbers: receiverNumbers,
Content: massage,
}
smsS.CreateSMS(smsHistoryRecord)
}),
Repetitions: repetitionCount,
Counter: 0,
StopOnFinish: true,
}
entryID := CronJobRunner.Schedule(parsedSchedule, job)
job.EntryID = entryID
return int(entryID), nil
}