// Author: NiuJiuRu
// Email: niujiuru@qq.com

package singletask

import "sync/atomic"

type OnceTask struct {
	running atomic.Bool
}

func (t *OnceTask) Run(f func(), async bool) {
	if !t.running.CompareAndSwap(false, true) {
		return
	}

	runFunc := func() {
		defer t.running.Store(false)
		f()
	}

	if async {
		go runFunc()
	} else {
		runFunc()
	}
}

func (t *OnceTask) IsRunning() bool {
	return t.running.Load()
}
