Files
ark/server/internal/infrastructure/scheduler/gocron/service.go
Marco Argentieri 1b0252f3e4 Migrate to Go Workspaces (#243)
* api-spec: move the api-spec to root and init go.mod

* go mod tidy

* move buf files in the root as well

* gh action for api-spec changes only

* gh action for api-spec on push and pr

* introduce go.work and remove all replaces

* solve dependencies and force btcd/btcec@v2.3.3

* go work sync

* force btcd/btcec@v2.3.3

* go mod tidy
2024-08-13 03:27:41 +02:00

46 lines
961 B
Go

package scheduler
import (
"fmt"
"time"
"github.com/ark-network/ark/server/internal/core/ports"
"github.com/go-co-op/gocron"
)
type service struct {
scheduler *gocron.Scheduler
}
func NewScheduler() ports.SchedulerService {
svc := gocron.NewScheduler(time.UTC)
return &service{svc}
}
func (s *service) Start() {
s.scheduler.StartAsync()
}
func (s *service) Stop() {
s.scheduler.Stop()
}
func (s *service) ScheduleTask(interval int64, immediate bool, task func()) error {
if immediate {
_, err := s.scheduler.Every(int(interval)).Seconds().Do(task)
return err
}
_, err := s.scheduler.Every(int(interval)).Seconds().WaitForSchedule().Do(task)
return err
}
func (s *service) ScheduleTaskOnce(at int64, task func()) error {
delay := at - time.Now().Unix()
if delay < 0 {
return fmt.Errorf("cannot schedule task in the past")
}
_, err := s.scheduler.Every(int(delay)).Seconds().WaitForSchedule().LimitRunsTo(1).Do(task)
return err
}