增加定时任务 处理异常

This commit is contained in:
2024-08-30 11:55:19 +08:00
parent aa3f9e8711
commit bfb284c4cc
30 changed files with 945 additions and 336 deletions

View File

@@ -0,0 +1,31 @@
package init_db_data
import (
"fmt"
"os"
)
type InitDBFunc interface {
Init() (err error)
}
// 初始化数据库
func initDB(InitDBFunctions ...InitDBFunc) (err error) {
for _, v := range InitDBFunctions {
err = v.Init()
if err != nil {
return err
}
}
return nil
}
func InitDbData() {
err := initDB(initPeakValleyTimeBlockData)
if err != nil {
fmt.Println("[-]初始化基础数据失败:", err)
os.Exit(0)
}
}
//

View File

@@ -0,0 +1,56 @@
package init_db_data
import (
"energy-management-system/global"
peak_valley_model "energy-management-system/model/peak-valley"
"github.com/gookit/color"
"gorm.io/gorm"
)
type InitPeakValleyTimeBlockData struct{}
var initPeakValleyTimeBlockData = new(InitPeakValleyTimeBlockData)
// type api struct{}
func buildData() (dataList []*peak_valley_model.PeakValleyTimeBlock) {
// 一天有24小时即1440分钟
totalMinutes := 24 * 60
// 时间块的持续时间10分钟
blockDuration := 10
// 遍历一天中的所有时间块
for i := 0; i < totalMinutes; i += blockDuration {
startTime := i
endTime := i + blockDuration
dataList = append(dataList, &peak_valley_model.PeakValleyTimeBlock{
StartTime: uint(startTime),
EndTime: uint(endTime),
})
}
return dataList
}
// Init 初始化用户数据
func (i *InitPeakValleyTimeBlockData) Init() error {
return global.Db.Transaction(func(tx *gorm.DB) error {
m := &peak_valley_model.PeakValleyTimeBlock{}
var count int64
err := tx.Model(&peak_valley_model.PeakValleyTimeBlock{}).Count(&count).Error
if err != nil {
return err
}
if count == 144 {
color.Danger.Println("\n[PGSQL] --> " + m.TableName() + " 表的初始数据已存在!")
return nil
}
dataList := buildData()
if err := tx.Create(&dataList).Error; err != nil { // 遇到错误时回滚事务
return err
}
color.Info.Println("\n[PGSQL] --> " + m.TableName() + "表初始数据成功!")
return nil
})
}