🐛 fix cron bug

This commit is contained in:
loser 2024-03-30 22:58:42 +08:00
parent b2eb4edbd5
commit 6608d8e966
6 changed files with 124 additions and 88 deletions

View File

@ -34,7 +34,7 @@ func GetUser(ctx *gin.Context, u *app.User, dontResponse, dontCheck bool) {
// 需要跳过微信绑定检验 // 需要跳过微信绑定检验
if !dontCheck { if !dontCheck {
// 检查微信绑定 // 检查微信绑定
if u.WechatOpenId == nil || *u.WechatOpenId == "" { if u.WechatOpenId == "" {
log.Errorf("%v 未绑定微信", u.Nickname) log.Errorf("%v 未绑定微信", u.Nickname)
response.FailWithMessage("请先绑定微信", ctx) response.FailWithMessage("请先绑定微信", ctx)
ctx.Abort() ctx.Abort()

View File

@ -57,7 +57,7 @@ func (u *UserApi) BindingWeChat(ctx *gin.Context) {
// 解析成功,修改用户信息 // 解析成功,修改用户信息
loginUser.WechatUnionId = &unionId loginUser.WechatUnionId = &unionId
loginUser.WechatOpenId = &openId loginUser.WechatOpenId = openId
if err = userService.UpdateUserInfo(&loginUser); err != nil { if err = userService.UpdateUserInfo(&loginUser); err != nil {
log.Errorf("修改用户信息失败:%s", err.Error()) log.Errorf("修改用户信息失败:%s", err.Error())
r.FailWithMessage("系统错误,请稍后再试", ctx) r.FailWithMessage("系统错误,请稍后再试", ctx)

View File

@ -10,7 +10,7 @@ type User struct {
global.GVA_MODEL global.GVA_MODEL
Phone string `json:"phone" gorm:"index:deleted;type:varchar(255) not null comment '手机号'"` Phone string `json:"phone" gorm:"index:deleted;type:varchar(255) not null comment '手机号'"`
WechatUnionId *string `json:"wechat_union_id" gorm:"type:varchar(255) comment '微信UnionId'"` WechatUnionId *string `json:"wechat_union_id" gorm:"type:varchar(255) comment '微信UnionId'"`
WechatOpenId *string `json:"wechat_open_id" gorm:"type:varchar(255) comment '微信OpenId'"` WechatOpenId string `json:"wechat_open_id" gorm:"type:varchar(255) comment '微信OpenId'"`
Nickname string `json:"nickname" gorm:"type:varchar(255) comment '昵称'"` Nickname string `json:"nickname" gorm:"type:varchar(255) comment '昵称'"`
Avatar string `json:"avatar" gorm:"type:varchar(255) comment '头像'"` Avatar string `json:"avatar" gorm:"type:varchar(255) comment '头像'"`
Status constant.UserStatus `json:"status" gorm:"type:enum('NORMAL','DISABLE'); default:'NORMAL'; not null; comment:'状态 NORMAL-正常DISABLE-禁用'"` Status constant.UserStatus `json:"status" gorm:"type:enum('NORMAL','DISABLE'); default:'NORMAL'; not null; comment:'状态 NORMAL-正常DISABLE-禁用'"`

View File

@ -13,10 +13,23 @@ func InitTask() {
WxTask = gocron.NewScheduler(time.Local) WxTask = gocron.NewScheduler(time.Local)
// 每天凌晨1点执行 // 每天凌晨1点执行
_, _ = WxTask.Every(1).Day().At("01:00").Do(CheckUserSurgeryDate) // 检查用户是否已到手术日期 _, err := WxTask.Every(1).Day().At("01:00").Do(CheckUserSurgeryDate) // 检查用户是否已到手术日期
_, _ = WxTask.Every(1).Day().At("01:00").Do(SendMsg2User) if err != nil {
global.GVA_LOG.Error("检查用户是否已到手术日期定时任务创建失败", zap.Error(err))
}
_, err = WxTask.Every(1).Day().At("01:00").Do(SendMsg2User)
if err != nil {
global.GVA_LOG.Error("发送消息定时任务创建失败", zap.Error(err))
}
//_, err = WxTask.Every("1m").Do(MiniappSendMsg, "o9Fq_6_cYKvOWnyUM3McC11hWsTI", "测试", "测试", "测试")
_, err = WxTask.Every("1m").Do(SendMsg2User)
if err != nil {
global.GVA_LOG.Error("检查用户是否已到手术日期定时任务创建失败", zap.Error(err))
}
// 开启定时任务 // 开启定时任务
WxTask.StartAsync() WxTask.StartAsync()
global.GVA_LOG.Info("定时任务已开启", zap.Any("定时任务状态:", WxTask.IsRunning()))
global.GVA_LOG.Info("定时任务已开启", zap.Any("任务数量:", WxTask.Len())) global.GVA_LOG.Info("定时任务已开启", zap.Any("任务数量:", WxTask.Len()))
} }

View File

@ -5,53 +5,60 @@ import (
"miniapp/global" "miniapp/global"
"miniapp/model/app" "miniapp/model/app"
"miniapp/model/common" "miniapp/model/common"
"strconv"
"strings"
"time" "time"
) )
// CheckUserSurgeryDate 检查用户是否已到手术日期 // CheckUserSurgeryDate 检查用户是否已到手术日期
func CheckUserSurgeryDate() { func CheckUserSurgeryDate() {
var users []app.User go func() {
global.GVA_DB.Model(&app.User{}).Find(&users) global.GVA_LOG.Info("检查用户是否已到手术日期")
for _, user := range users { var users []app.User
parse, _ := time.Parse("2006-01-02", user.SurgeryTime) global.GVA_DB.Model(&app.User{}).Find(&users)
if time.Now().Sub(parse).Hours()/24 == 0 { for _, user := range users {
global.GVA_DB.Model(&app.User{}).Where("id = ?", user.ID).Updates(app.User{IsSurgery: 1}) parse, _ := time.Parse("2006-01-02", user.SurgeryTime)
if time.Now().Sub(parse).Hours()/24 == 0 {
global.GVA_DB.Model(&app.User{}).Where("id = ?", user.ID).Updates(app.User{IsSurgery: 1})
}
} }
} }()
} }
func SendMsg2User() { func SendMsg2User() {
WxTask.Clear() go func() {
global.GVA_LOG.Info("执行发送消息定时任务")
var ut []common.UserTodo
err := global.GVA_DB.Model(&common.UserTodo{}).Find(&ut).Error
if err != nil {
global.GVA_LOG.Error("定时任务获取用户Todo列表失败", zap.Error(err))
}
var ut []common.UserTodo for _, todo := range ut {
err := global.GVA_DB.Model(&common.UserTodo{}).Find(&ut).Error if strings.Compare(todo.RemindDay, time.Now().Format("2006-01-02")) == 0 {
if err != nil { // 创建定时任务
global.GVA_LOG.Error("定时任务获取用户Todo列表失败", zap.Error(err)) //WxTask := gocron.NewScheduler(time.Local)
} //Send(todo.UserId, todo.Content, todo.RemindTime, todo.Frequency)
user := app.User{}
for _, todo := range ut { err := global.GVA_DB.Model(&app.User{}).Where("id = ?", todo.UserId).Find(&user).Error
parse, _ := time.Parse("2006-01-02", todo.RemindDay)
if time.Now().Sub(parse).Hours()/24 == 0 {
// 创建定时任务
//WxTask := gocron.NewScheduler(time.Local)
//Send(todo.UserId, todo.Content, todo.RemindTime, todo.Frequency)
user := app.User{}
err := global.GVA_DB.Model(&app.User{}).Where("id = ?", todo.UserId).Find(&user).Error
if err != nil {
global.GVA_LOG.Error("定时任务获取用户信息失败:%s", zap.Error(err))
return
}
// 根据用户手术信息 发送提醒消息
if user.IsSurgery == 0 && todo.RemindPeriod == 0 && todo.IsFinish == 0 {
// 根据年月日时发送消息
_, err := WxTask.Every(1).Day().At(todo.RemindTime).Do(MiniappSendMsg, *user.WechatOpenId, todo.Content, todo.RemindPeriod, todo.RemindTime)
if err != nil { if err != nil {
global.GVA_LOG.Error("定时任务创建失败:%s", zap.Error(err)) global.GVA_LOG.Error("定时任务获取用户信息失败:%s", zap.Error(err))
return return
} }
// 根据用户手术信息 发送提醒消息
if user.IsSurgery == 0 && todo.RemindPeriod == 0 && todo.IsFinish == 0 {
// 根据年月日时发送消息
//job, err := WxTask.Every(1).Day().At(todo.RemindTime).Do(MiniappSendMsg, *user.WechatOpenId, todo.Content, todo.RemindPeriod, todo.RemindTime)
job, err := WxTask.Every(1).Day().At(todo.RemindTime).Do(MiniappSendMsg, strconv.Itoa(int(user.ID)), strconv.Itoa(int(todo.ID)))
global.GVA_LOG.Info("定时任务创建成功", zap.Any("job", job))
if err != nil {
global.GVA_LOG.Error("定时任务创建失败:%s", zap.Error(err))
return
}
}
} }
} }
} }()
} }

View File

@ -41,7 +41,7 @@ func SendMsg(userId int) {
parse, _ := time.Parse("2006-01-02", user.SurgeryTime) parse, _ := time.Parse("2006-01-02", user.SurgeryTime)
if time.Now().Sub(parse).Hours()/24 <= -3 { if time.Now().Sub(parse).Hours()/24 <= -3 {
for _, todo := range userTodo { for _, todo := range userTodo {
jbo, _ := WxTask.Every(1).Day().At(todo.RemindTime).Do(MiniappSendMsg, *user.WechatOpenId, todo.Content, todo.RemindPeriod, todo.RemindTime) // 检查用户待办事项 jbo, _ := WxTask.Every(1).Day().At(todo.RemindTime).Do(MiniappSendMsg, user.WechatOpenId, todo.Content, todo.RemindPeriod, todo.RemindTime) // 检查用户待办事项
s := strings.Split("一天3次", "")[2] s := strings.Split("一天3次", "")[2]
// 将s转为int类型 // 将s转为int类型
atoi, _ := strconv.Atoi(s) atoi, _ := strconv.Atoi(s)
@ -52,68 +52,84 @@ func SendMsg(userId int) {
} }
} }
func MiniappSendMsg(openId string, context string, frequency string, remindTime string) { func MiniappSendMsg(userId string, utId string) {
sdk := weapp.NewClient(global.GVA_CONFIG.MiniApp.AppId, global.GVA_CONFIG.MiniApp.AppSecret) sdk := weapp.NewClient(global.GVA_CONFIG.MiniApp.AppId, global.GVA_CONFIG.MiniApp.AppSecret)
var msgDatas []msg.SendRequest go func() {
//判断context是否超过20个字符 user := app.User{}
if len(context)/3 >= 19 { err := global.GVA_DB.Model(&app.User{}).Where("id = ?", userId).Find(&user).Error
text := strings.Split(context, "药品") if err != nil {
for i := 1; i < len(text); i++ { global.GVA_LOG.Error("定时任务获取用户信息失败:%s", zap.Error(err))
return
}
var ut common.UserTodo
err = global.GVA_DB.Model(&common.UserTodo{}).Where("id = ?", utId).First(&ut).Error
if err != nil {
global.GVA_LOG.Error("定时任务获取用户Todo列表失败", zap.Error(err))
}
var msgDatas []msg.SendRequest
//判断context是否超过20个字符
if len(ut.Content)/3 >= 19 {
text := strings.Split(ut.Content, "药品")
for i := 1; i < len(text); i++ {
msgData := msg.SendRequest{
ToUser: user.WechatOpenId,
TemplateID: "PgxoZOOSDgBcmIGd_EVLDnYUmL3eu6NQTAZCsHQeuWY",
Page: "/page/index/todo",
MiniprogramState: msg.MiniprogramStateTrial,
Data: msg.SendData{
"thing1": msg.SendValue{Value: text[i]},
"time2": msg.SendValue{Value: ut.RemindTime},
"short_thing17": msg.SendValue{Value: ut.Frequency},
"time15": msg.SendValue{Value: time.Now().Format("2006-01-02 15:04:05")},
},
}
msgDatas = append(msgDatas, msgData)
}
} else {
msgData := msg.SendRequest{ msgData := msg.SendRequest{
ToUser: openId, ToUser: user.WechatOpenId,
TemplateID: "PgxoZOOSDgBcmIGd_EVLDnYUmL3eu6NQTAZCsHQeuWY", TemplateID: "PgxoZOOSDgBcmIGd_EVLDnYUmL3eu6NQTAZCsHQeuWY",
Page: "/page/index/todo", Page: "/page/index/todo",
MiniprogramState: msg.MiniprogramStateTrial, MiniprogramState: msg.MiniprogramStateTrial,
Data: msg.SendData{ Data: msg.SendData{
"thing1": msg.SendValue{Value: text[0] + text[i]}, "thing1": msg.SendValue{Value: ut.Content},
"time2": msg.SendValue{Value: remindTime}, "time2": msg.SendValue{Value: ut.RemindTime},
"short_thing17": msg.SendValue{Value: frequency}, "short_thing17": msg.SendValue{Value: ut.Frequency},
"time15": msg.SendValue{Value: time.DateTime}, "time15": msg.SendValue{Value: time.Now().Format("2006-01-02 15:04:05")},
}, },
} }
msgDatas = append(msgDatas, msgData) send, err := sdk.NewSubscribeMessage().Send(&msgData)
} if err != nil {
} else { return
msgData := msg.SendRequest{ }
ToUser: openId,
TemplateID: "PgxoZOOSDgBcmIGd_EVLDnYUmL3eu6NQTAZCsHQeuWY", err = send.GetResponseError()
Page: "/page/index/todo", if err != nil {
MiniprogramState: msg.MiniprogramStateTrial, fmt.Printf("微信返回错误: %#v", err)
Data: msg.SendData{ return
"thing1": msg.SendValue{Value: context}, }
"time2": msg.SendValue{Value: remindTime}, global.GVA_LOG.Info("发送成功: %#v", zap.Any("返回结果: %#v", send))
"short_thing17": msg.SendValue{Value: frequency},
"time15": msg.SendValue{Value: time.DateTime},
},
} }
send, err := sdk.NewSubscribeMessage().Send(&msgData) for i := 0; i < len(msgDatas); i++ {
if err != nil { send, err := sdk.NewSubscribeMessage().Send(&msgDatas[i])
return if err != nil {
} return
}
err = send.GetResponseError() err = send.GetResponseError()
if err != nil { if err != nil {
fmt.Printf("微信返回错误: %#v", err) fmt.Printf("微信返回错误: %#v", err)
return return
}
global.GVA_LOG.Info("发送成功: %#v", zap.Any("返回结果: %#v", send))
} }
global.GVA_LOG.Info("发送成功: %#v", zap.Any("返回结果: %#v", send)) }()
}
for i := 0; i < len(msgDatas); i++ {
send, err := sdk.NewSubscribeMessage().Send(&msgDatas[i])
if err != nil {
return
}
err = send.GetResponseError()
if err != nil {
fmt.Printf("微信返回错误: %#v", err)
return
}
global.GVA_LOG.Info("发送成功: %#v", zap.Any("返回结果: %#v", send))
}
} }