-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
98 lines (82 loc) · 2.01 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
package main
import (
"database/sql"
"github.com/SCH-Discord/NoticeNotifier/crawler/libraryN"
"github.com/SCH-Discord/NoticeNotifier/crawler/mainN"
"github.com/SCH-Discord/NoticeNotifier/crawler/studentN"
"github.com/SCH-Discord/NoticeNotifier/crawler/swN"
"github.com/SCH-Discord/NoticeNotifier/database"
"github.com/SCH-Discord/NoticeNotifier/database/model"
"log"
"math/rand"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
log.SetFlags(log.Ldate | log.Lmicroseconds)
sqlDb, err := setupDatabase()
if err != nil {
log.Fatal(err)
}
defer sqlDb.Close()
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
log.Println("Ctrl + C를 통해 종료할 수 있습니다.")
loop:
for {
select {
case <-done:
log.Println("프로그램을 종료합니다.")
break loop
case <-time.After(timeUntilNextRun()):
go doTask()
}
}
}
func doTask() {
log.Println("Starting a scheduled task")
mainN.Scrape()
swN.Scrape()
studentN.Scrape()
libraryN.Scrape()
log.Println("Completed a scheduled task")
}
// 데이터 베이스 설정
func setupDatabase() (*sql.DB, error) {
db := database.ConnectionDB()
sqlDb, err := db.DB()
if err != nil {
return nil, err
}
err = db.AutoMigrate(&model.Subscriber{})
if err != nil {
sqlDb.Close()
return nil, err
}
err = db.AutoMigrate(&model.Latest{})
if err != nil {
sqlDb.Close()
return nil, err
}
log.Println("ORM ready")
return sqlDb, nil
}
// AM 10시 ~ PM 8시
func nextRunHour(currentHour int) int {
if currentHour < 10 || currentHour > 19 {
return 10
}
return currentHour + 1
}
// 다음 실행 시간 까지 남은 시간리턴
func timeUntilNextRun() time.Duration {
now := time.Now()
targetTime := time.Date(now.Year(), now.Month(), now.Day(), nextRunHour(now.Hour()), rand.Intn(5), rand.Intn(59), now.Nanosecond(), now.Location())
if now.After(targetTime) {
targetTime = targetTime.Add(24 * time.Hour)
}
log.Println("다음실행 시간:", targetTime)
return targetTime.Sub(now)
}