Skip to content

Commit

Permalink
refactor(crontab/v2): Refactor v2 version (#95)
Browse files Browse the repository at this point in the history
* refactor(crontab/v2): Refactor v2 version

Signed-off-by: Flc゛ <[email protected]>

* refactor(crontab/v2): Refactor v2 version

Signed-off-by: Flc゛ <[email protected]>

---------

Signed-off-by: Flc゛ <[email protected]>
  • Loading branch information
flc1125 authored Feb 14, 2024
1 parent f1577e5 commit 3a46d53
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 0 deletions.
6 changes: 6 additions & 0 deletions crontab/v2/job.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package v2 //nolint:typecheck

type Job interface {
Exp() string // Expression
Run() // Handler
}
1 change: 1 addition & 0 deletions crontab/v2/null_jog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package v2
27 changes: 27 additions & 0 deletions crontab/v2/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package v2

import (
"context"

"github.com/robfig/cron/v3"
)

type Server struct {
*cron.Cron
}

func NewServer(c *cron.Cron) *Server {
return &Server{
Cron: c,
}
}

func (s *Server) Start(context.Context) error {
s.Cron.Run()
return nil
}

func (s *Server) Stop(context.Context) error {
s.Cron.Stop()
return nil
}
55 changes: 55 additions & 0 deletions crontab/v2/server_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package v2

import (
"context"
"testing"
"time"

"github.com/robfig/cron/v3"
)

type mockJob struct{}

func RegisterMockJob(srv *Server) {
n := newMockJob()
_, _ = srv.AddJob(n.Exp(), n)
}

func newMockJob() *mockJob {
return &mockJob{}
}

func (j *mockJob) Exp() string {
return "* * * * * *"
}

func (j *mockJob) Run() {
data <- "Hello World!"
}

var (
ctx = context.Background()
data = make(chan string, 1)
)

func TestCrontab(t *testing.T) {
srv := NewServer(cron.New(
cron.WithSeconds(),
))

RegisterMockJob(srv)

go srv.Start(ctx) //nolint:errcheck
defer srv.Stop(ctx) //nolint:errcheck

ctx, cancel := context.WithTimeout(ctx, time.Second*2)
defer cancel()

select {
case <-ctx.Done():
t.Error("Crontab test timeout")
return
case msg := <-data:
t.Log(msg)
}
}

0 comments on commit 3a46d53

Please sign in to comment.