|
- package task
-
- import (
- "applet/app/db"
- taskMd "applet/app/task/md"
- "code.fnuoos.com/EggPlanet/egg_models.git/src/implement"
- "code.fnuoos.com/EggPlanet/egg_models.git/src/model"
- "fmt"
- "time"
-
- "applet/app/utils/logx"
- "github.com/robfig/cron/v3"
- "xorm.io/xorm"
- )
-
- var (
- timer *cron.Cron
- jobs = map[string]func(*xorm.Engine){}
- baseEntryId cron.EntryID
- entryIds []cron.EntryID
- taskCfgList *[]model.CronTask
- ch = make(chan int, 30)
- workerNum = 15 // 并发数量
- )
-
- func Init() {
- // 初始化任务列表
- initTasks()
- var err error
- timer = cron.New()
- // reload为初始化数据库方法
- if baseEntryId, err = timer.AddFunc("@every 30m", reload); err != nil {
- _ = logx.Fatal(err)
- }
- }
-
- func Run() {
- reload()
- timer.Start()
- _ = logx.Info("auto tasks running...")
- }
-
- func reload() {
- cronTaskDb := implement.NewCronTaskDb(db.Db)
- taskCfgList = cronTaskDb.MapCrontabCfg()
-
- if len(*taskCfgList) > 0 {
- // 删除原有所有任务
- if len(entryIds) > 0 {
- for _, v := range entryIds {
- if v != baseEntryId {
- timer.Remove(v)
- }
- }
- entryIds = nil
- }
- var (
- entryId cron.EntryID
- err error
- )
- // 添加任务
- for _, v := range *taskCfgList {
- if _, ok := jobs[v.Key]; ok && v.Val != "" {
- fmt.Println(v.Val)
- if entryId, err = timer.AddFunc(v.Val, doTask(v.Key)); err == nil {
- entryIds = append(entryIds, entryId)
- }
- }
- }
- }
- }
-
- func doTask(fnName string) func() {
- return func() {
- begin := time.Now().Local()
- jobs[fnName](db.Db)
- end := time.Now().Local()
- logx.Infof(
- "[%s] AutoTask <%s> started at <%s>, ended at <%s> duration <%s>",
- fnName,
- begin.Format("2006-01-02 15:04:05.000"),
- end.Format("2006-01-02 15:04:05.000"),
- time.Duration(end.UnixNano()-begin.UnixNano()).String(),
- )
- }
- }
-
- // 增加自动任务队列
- func initTasks() {
- jobs[taskMd.CronEggEnergyAutoRecordPrices] = taskEggEnergyAutoRecordPrices
- jobs[taskMd.CronEggEnergyDealPlatformRevenueData] = taskEggEnergyDealPlatformRevenueData
- jobs[taskMd.CronEggEnergyDealFundData] = taskEggEnergyDealFundData
- jobs[taskMd.CronEggEnergyUserEggScore] = taskCronEggEnergyUserEggScore
- jobs[taskMd.CornEggEnergyAutoReleaseTeamEggEnergy] = taskEggEnergyAutoReleaseTeamEggEnergy // 蛋蛋能量-自动释放团队蛋蛋能量到个人能量
- jobs[taskMd.CornSettlementStarLevelDividends] = taskEggEnergySettlementStarLevelDividends // 蛋蛋能量-结算星级分红
- jobs[taskMd.CornEggEnergyDealUserPublicPlatoonPunish] = taskEggEnergyDealUserPublicPlatoonPunish // 蛋蛋能量-公排处罚
- jobs[taskMd.CornEggEnergyAutoAdjustPrice] = taskEggEnergyAutoAdjustPrice // 蛋蛋能量-自动调整价格
- jobs[taskMd.CornEggEnergyAutoCommunityDividends] = taskEggEnergyCommunityDividends // 蛋蛋能量-社区分红
- }
|