package main import ( "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" "time" "github.com/iris-contrib/middleware/cors" "github.com/kataras/iris/v12" ) const INTERVAL_PERIOD time.Duration = 24 * time.Hour const HOUR_TO_TICK int = 0 const MINUTE_TO_TICK int = 1 const SECOND_TO_TICK int = 03 type jobTicker struct { t *time.Timer } func main() { go mainTicker() app := iris.New() crs := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, // allows everything, use that to change the hosts. AllowCredentials: false, }) v1 := app.Party("/", crs).AllowMethods(iris.MethodOptions) // <- important for the preflight. { v1.Post("/", func(ctx iris.Context) { var data map[string]interface{} err := ctx.ReadJSON(&data) if err != nil { ctx.StopWithStatus(iris.StatusBadRequest) ctx.WriteString(err.Error()) ctx.WriteString(err.Error()) return } file, _ := json.MarshalIndent(data, "", " ") curTime := time.Now().UTC() err = ioutil.WriteFile(fmt.Sprintf("./%s/%v", curTime.Format("2006-01-02"), curTime.UnixNano())+"_data.json", file, 0644) if err != nil { t := time.Now().UTC() newpath := filepath.Join(".", t.Format("2006-01-02")) os.MkdirAll(newpath, os.ModePerm) _ = ioutil.WriteFile(fmt.Sprintf("./%s/%v", curTime.Format("2006-01-02"), curTime.UnixNano())+"_data.json", file, 0644) } ctx.JSON(iris.Map{ "success": true, }) }) } app.Listen(":80") } func getNextTickDuration() time.Duration { now := time.Now().UTC() nextTick := time.Date(now.Year(), now.Month(), now.Day(), HOUR_TO_TICK, MINUTE_TO_TICK, SECOND_TO_TICK, 0, time.UTC) if nextTick.Before(now) { nextTick = nextTick.Add(INTERVAL_PERIOD) } return nextTick.Sub(time.Now().UTC()) } func NewJobTicker() jobTicker { t := time.Now().UTC() newpath := filepath.Join(".", t.Format("2006-01-02")) os.MkdirAll(newpath, os.ModePerm) return jobTicker{time.NewTimer(getNextTickDuration())} } func (jt jobTicker) updateJobTicker() { fmt.Println("next tick here") t := time.Now().UTC() newpath := filepath.Join(".", t.Format("2006-01-02")) os.MkdirAll(newpath, os.ModePerm) jt.t.Reset(getNextTickDuration()) } func mainTicker() { jt := NewJobTicker() for { <-jt.t.C fmt.Println(time.Now(), "- just ticked") jt.updateJobTicker() } }