cycle-scheduler/main.go
2024-09-24 16:45:09 +02:00

126 lines
2.3 KiB
Go

package main
import (
"context"
"cycle-scheduler/internal/job"
"cycle-scheduler/internal/scheduler"
"encoding/json"
"errors"
"fmt"
"math/rand/v2"
"os"
"os/signal"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
const (
MaxWorkers = 5
Interval = 2000 * time.Millisecond
)
func initLogger() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
log.Logger = log.With().Caller().Logger().Output(zerolog.ConsoleWriter{Out: os.Stderr})
}
func main() {
initLogger()
ctx, stop := signal.NotifyContext(
context.Background(),
os.Interrupt,
os.Kill,
)
defer stop()
s := scheduler.NewSchedulerCycle(ctx, Interval, MaxWorkers)
// pending test
for i := 0; i < 20; i++ {
go func(i int) {
time.Sleep(time.Duration(i) * time.Second)
s.Delay(func(ctx context.Context) error {
time.Sleep(4 * time.Second) //nolint:mnd // test purpose
if rand.IntN(10)%2 == 0 { //nolint:gosec,mnd // test prupose
return job.ErrJobNotCompletedYet
}
return nil
})
}(i)
}
// abort test
j := s.Delay(func(ctx context.Context) error {
time.Sleep(4 * time.Second) //nolint:mnd // test purpose
select {
case <-ctx.Done():
return ctx.Err()
default:
}
return job.ErrJobNotCompletedYet
})
go func() {
time.Sleep(2 * time.Second) //nolint:mnd // test purpose
s.Abort(j)
}()
// abort test 2
j2 := s.Delay(func(ctx context.Context) error {
time.Sleep(time.Second)
select {
case <-ctx.Done():
return ctx.Err()
default:
}
return job.ErrJobNotCompletedYet
})
go func() {
time.Sleep(10 * time.Second) //nolint:mnd // test purpose
s.Abort(j2)
}()
// error test
s.Delay(func(ctx context.Context) error {
time.Sleep(5 * time.Second) //nolint:mnd // test purpose
return errors.New("err")
})
// success test
go func() {
time.Sleep(10 * time.Second) //nolint:mnd // test purpose
s.Delay(func(ctx context.Context) error {
time.Sleep(5 * time.Second) //nolint:mnd // test purpose
return nil
})
}()
go func() {
for {
time.Sleep(2 * time.Second) //nolint:mnd // test purpose
if s.TasksDone() {
s.Stop()
return
}
}
}()
<-s.Done()
ts := s.GetTasksDetails()
for _, t := range ts {
c, err := json.Marshal(&t)
if err != nil {
log.Err(err).Str("task", t.ID.String()).Msg("unable to parse task details into JSON")
continue
}
fmt.Println(string(c))
}
}