package standby_ctrl

import (
	"context"
	"go.uber.org/zap"
	"time"
)

// Interval 循环间隔控制器
func Interval(interval int64, play func(c context.Context) error) func(c context.Context) error {
	return func(c context.Context) error {
		zap.S().Infoln("待机间隔控制器: ", interval)
		defer zap.S().Infoln("待机间隔控制器结束: ", interval)

		for {
			err := play(c)
			if err != nil {
				zap.S().Errorln("执行后续操作异常: ", err)
			}
			if interval > 0 {
				select {
				case <-c.Done():
					return nil
				case <-time.After(time.Duration(interval) * time.Second):
				}
			} else {
				select {
				case <-c.Done():
					return nil
				default:
					// 避免忙循环，短暂休眠
					time.Sleep(10 * time.Millisecond)
				}
			}
		}
	}
}
