-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscheduler_sqlite.go
More file actions
94 lines (77 loc) · 1.93 KB
/
scheduler_sqlite.go
File metadata and controls
94 lines (77 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"time"
"github.com/hyp3rd/go-again/pkg/scheduler"
)
const (
pollEvery = 20 * time.Millisecond
pollTimeout = 3 * time.Second
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), pollTimeout)
defer cancel()
dbPath := filepath.Join(os.TempDir(), "go-again-scheduler-example.db")
_ = os.Remove(dbPath)
storage, err := scheduler.NewSQLiteJobsStorageWithOptions(
ctx,
dbPath,
scheduler.WithSQLiteHistoryMaxAge(24*time.Hour),
scheduler.WithSQLiteHistoryMaxRowsPerJob(100),
)
if err != nil {
fmt.Fprintf(os.Stderr, "create sqlite storage failed: %v\n", err)
return
}
defer func() {
_ = storage.Close()
_ = os.Remove(dbPath)
}()
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer target.Close()
s := scheduler.NewScheduler(
ctx,
scheduler.WithJobsStorage(storage),
scheduler.WithURLValidator(nil), // allow local endpoint for example usage
)
defer s.Stop(ctx)
jobID, err := s.Schedule(
ctx,
scheduler.Job{
Schedule: scheduler.Schedule{
Every: pollEvery,
MaxRuns: 1,
},
Request: scheduler.Request{
Method: http.MethodGet,
URL: target.URL,
},
})
if err != nil {
fmt.Fprintf(os.Stderr, "schedule failed: %v\n", err)
return
}
deadline := time.Now().Add(pollTimeout)
for time.Now().Before(deadline) {
status, ok := s.JobStatus(ctx, jobID)
if ok && status.State == scheduler.JobStateCompleted {
pruned, pruneErr := storage.PruneHistory(ctx)
if pruneErr != nil {
fmt.Fprintf(os.Stderr, "prune history failed: %v\n", pruneErr)
return
}
fmt.Printf("completed: job=%s runs=%d\n", jobID, status.Runs)
fmt.Printf("pruned history rows: %d\n", pruned)
return
}
time.Sleep(pollEvery)
}
fmt.Fprintln(os.Stderr, "timed out waiting for completed status")
}