package vqdcms

import (
	"context"
	"time"
)

type Worker struct {
	ctx    context.Context
	cancel context.CancelFunc
}

func NewWorker() *Worker {
	ctx, cancel := context.WithCancel(context.Background())
	return &Worker{
		ctx:    ctx,
		cancel: cancel,
	}
}

func (w *Worker) Stop() {
	w.cancel() // 显式调用cancel停止worker
}

type Scheduler struct {
	stopChan chan struct{}
}

func NewScheduler() *Scheduler {
	return &Scheduler{
		stopChan: make(chan struct{}),
	}
}

func (s *Scheduler) Start(interval time.Duration, task func()) {
	go func() {
		ticker := time.NewTicker(interval)
		defer ticker.Stop()

		for {
			select {
			case <-ticker.C:
				task()
			case <-s.stopChan:
				return
			}
		}
	}()
}

func (s *Scheduler) Stop() {
	if s.stopChan != nil {
		close(s.stopChan)
		s.stopChan = nil // 防止重复关闭
	}
}
