文章目录
- 前言
- 一、代码
- 二、DB
- 三、效果
前言
今天观摩前辈的代码,看到time.Timer的使用,发现对于定时任务可以这样做达到js的setInterval()效果
一、代码
package mainimport ("fmt""gorm.io/driver/postgres""gorm.io/gorm""gorm.io/gorm/schema""time"
)type Cchecker struct {timer *time.TimerendChan chan bool
}func main() {go checkFunc()for {}
}
func checkFunc() {var d Ccheckerd.timer = time.NewTimer(time.Second * time.Duration(2))d.endChan = make(chan bool, 1)for {select {case <-d.timer.C:d.timer.Reset(time.Second * time.Duration(2))if i := check(); i == 1 {fmt.Println("数据库已更新")d.endChan <- true} else {fmt.Println("数据库未更新")}case <-d.endChan:return}}
}func check() int {dataSourceName := fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%s timezone=%s sslmode=disable","postgres", "xxxx", "xxxx", "xxxxxxxxx", "xxxxx", "Asia/shanghai")db, err := gorm.Open(postgres.Open(dataSourceName), &gorm.Config{NamingStrategy: schema.NamingStrategy{SingularTable: true},PrepareStmt: true,})if err != nil {fmt.Println("err")}var i interr = db.Raw("SELECT flag FROM idp where id = 1").Scan(&i).Errorreturn i
}
二、DB
三、效果
手动更改数据库flag为非1时,检测出数据库更新信息
如图: