项目介绍
基于 golang 的一个定时消息推送系统。
工作原理:CALLBACK
流程:系统由 阻塞协程 触发器 任务管理器 三部分组成。
实现流程: 务管理内有一个任务列表,通过注册任务,来向任务列表添加任务。然后启动一个阻塞协程去轮询任务列表,并且将当前时间通知到每一个任务。
具体触发操作在任务函数内定义。
程序流程
效果图
实现
生命周期
// recycle 生命周期
func (this *TaskManager) start() {
go func() {
for true {
time.Sleep(1 * time.Second)
for index := range this.timeList {
go this.timeList[index](time.Now())
}
}
}()
// 阻塞
log.Println("服务已启动...")
go func() {
for index := range this.timeList {
log.Println(fmt.Sprintf("taskList[%v]:%v", index, this.timeList[index]))
}
}()
select {}
}
任务管理器
package main
import (
"fmt"
"log"
"time"
)
// callback
type CALL func(time2 time.Time)
type TaskManager struct {
timeList []CALL
}
// 创建一个任务管理器
func NewTaskManager() *TaskManager {
return &TaskManager{}
}
// 添加一个函数到函数列表
func (this *TaskManager) addSub(call CALL) {
this.timeList = append(this.timeList, call)
}
注册任务
package main
import (
"fmt"
"time"
)
func RegisterSub(manager *TaskManager) *TaskManager {
// 注册早上推送
manager.addSub(func(t time.Time) {
//year, mon, day := t.Date()
h := t.Hour()
m := t.Minute()
s := t.Second()
weekDay := int(t.Weekday()) - 1
// 整点 7.40
if h == 7 && m == 40 && s == 0 {
pushMsgToWechat("上午课表", fmt.Sprintf("<h2>8:20 %v</h2> \n <h2>10:20 %v</h2>", courseList[weekDay].A, courseList[weekDay].B))
} else if h == 13 && m == 40 && s == 0 { // 中午
pushMsgToWechat("下午课表", fmt.Sprintf("<h2>14:00 %v</h2> \n <h2>16:00 %v</h2>", courseList[weekDay].C, courseList[weekDay].D))
} else if h == 18 && m == 40 && s == 0 && courseList[weekDay].E != "none" { // 晚自习
pushMsgToWechat("晚上课表", fmt.Sprintf("<h2>14:00 %v</h2>", courseList[weekDay].E))
}
})
return manager
}
推送服务
// 推送消息到微信
func pushMsgToWechat(title string, content string) {
resp, err := http.PostForm("http://www.pushplus.plus/send", url.Values{
"token": {TOKEN},
"title": {title},
"content": {content},
})
if err != nil {
log.Println(err)
}
defer resp.Body.Close()
}
课表解析器
func loadJson() []Item {
jsonStr := `{"data":[{"1":"离散数学(理论) A-401","2":"计算机网络(理论) A-401","3":"python程序设计(理论) 综合3","4":"none","5":"none"},{"1":"软件工程(理论) B-301","2":"none","3":"计算机组成原理(理论) 综合7","4":"none","5":"大数据概论(理论) 综合3"},{"1":"python程序设计(理论) 综合7","2":"none","3":"none","4":"java程序设计基础(理论) B-302","5":"计算机网络基础(理论) B-206"},{"1":"大数据概论(理论) S-405","2":"离散数学(理论) 综合6","3":"none","4":"none","5":"none"},{"1":"计算机组成原理(理论) A-309","2":"java程序设计 D-201","3":"none","4":"none","5":"none"}]}`
type Items struct {
List []Item `json:"data"`
}
items := Items{}
err := json.Unmarshal([]byte(jsonStr), &items)
if err != nil {
log.Println(err)
}
return items.List
}
部署
export GOOS=linux
export GOARCH=amd64
go build