Skip to content

Commit c6ff4c1

Browse files
committed
refactor code and update readme
1 parent 30bf8df commit c6ff4c1

File tree

6 files changed

+57
-79
lines changed

6 files changed

+57
-79
lines changed

README.md

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# TaskScheduler
2-
3-
This is use to complete task(function) in parllel to complete task fast. Each task consist of two things function that need to perform and metaId that use to fetch meta from the database using the metaId. Meta is use in the function to perform task. Each task(function) may or may not need parameters.
2+
This can use to peform tasks, with option to retry if failed and also peform task after some delay, in parallel to complete task quickly. Each task consist of two things function that need to perform and metaId that use to fetch meta from the database using the metaId. Meta is use in the function to perform task. Each task(function) may or may not need parameters.
43

54
Use go get github.com/amitiwary999/task-scheduler to fetch this module in your code.
65

@@ -9,8 +8,23 @@ import this library and then init the task scheduler
98
```
109
import ("github.com/amitiwary999/task-scheduler/scheduler")
1110
12-
tsk := scheduler.NewTaskScheduler(doneChannel, postgresUrl, poolLimit, workerCount, taskQueueLimit)
13-
go tsk.StartScheduler()
11+
tconf := &scheduler.TaskConfig{
12+
MaxTaskWorker: 10,
13+
TaskQueueSize: 10000,
14+
Done: done,
15+
RetryTimeDuration: time.Duration(5 * time.Second),
16+
FuncGenerator: generateFunc,
17+
}
18+
tsk := scheduler.NewTaskScheduler(tconf)
19+
/**
20+
storage use to save the task so that we can fetch fail task later to retry again. Scheduler need StorageClient interface so that it can perform the storage operation. So before InitScheduler call make sure to get a StorageClient interface. We provide the function to create postgres db client. Will add support for the other storage later.
21+
*/
22+
dbClient, err := storage.NewPostgresClient(os.Getenv("POSTGRES_URL"), int16(poolLimit), "jobdetail")
23+
tsk.InitScheduler(dbClient)
24+
25+
/**
26+
After init scheduler successfully, Task can be submit. Each task has Meta of task and TaskFn function to perform the task.
27+
*/
1428
meta := model.TaskMeta{
1529
MetaId: id,
1630
Delay: intValue(after how much delay task need to perform, optional)

cmd/main.go

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import (
1111

1212
model "github.com/amitiwary999/task-scheduler/model"
1313
scheduler "github.com/amitiwary999/task-scheduler/scheduler"
14-
14+
storage "github.com/amitiwary999/task-scheduler/storage"
1515
"github.com/joho/godotenv"
1616
)
1717

@@ -40,17 +40,14 @@ func main() {
4040
gracefulShutdown := make(chan os.Signal, 1)
4141
signal.Notify(gracefulShutdown, syscall.SIGINT, syscall.SIGTERM)
4242
tconf := &scheduler.TaskConfig{
43-
PostgUrl: os.Getenv("POSTGRES_URL"),
44-
PoolLimit: int16(poolLimit),
4543
MaxTaskWorker: 10,
4644
TaskQueueSize: 10000,
47-
JobTableName: "jobdetail",
4845
Done: done,
4946
RetryTimeDuration: time.Duration(5 * time.Second),
5047
FuncGenerator: generateFunc,
5148
}
5249
tsk := scheduler.NewTaskScheduler(tconf)
53-
postgClient, err := tsk.InitStorage()
50+
postgClient, err := storage.NewPostgresClient(os.Getenv("POSTGRES_URL"), int16(poolLimit), "jobdetail")
5451
if err != nil {
5552
return
5653
}

cmd/main_test.go

Lines changed: 27 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ import (
44
"errors"
55
"fmt"
66
"math/rand"
7-
"os"
8-
"strconv"
97
"sync"
108
"testing"
119
"time"
@@ -60,44 +58,38 @@ func TestTaskScheduler(t *testing.T) {
6058
if err != nil {
6159
t.Errorf("error load env %v\n", err)
6260
}
63-
poolLimit, err := strconv.Atoi(os.Getenv("POSTGRES_POOL_LIMIT"))
61+
62+
done := make(chan int)
63+
tconf := &scheduler.TaskConfig{
64+
MaxTaskWorker: 10,
65+
TaskQueueSize: 10000,
66+
Done: done,
67+
RetryTimeDuration: time.Duration(3 * time.Second),
68+
FuncGenerator: testGenerateFunc,
69+
}
70+
tsk := scheduler.NewTaskScheduler(tconf)
71+
postgClient := dbStruct{}
72+
tsk.InitScheduler(postgClient)
6473
if err != nil {
65-
t.Errorf("error in the string conversion pool limit %v", err)
66-
} else {
67-
done := make(chan int)
68-
tconf := &scheduler.TaskConfig{
69-
PostgUrl: os.Getenv("POSTGRES_URL"),
70-
PoolLimit: int16(poolLimit),
71-
MaxTaskWorker: 10,
72-
TaskQueueSize: 10000,
73-
JobTableName: "jobdetail",
74-
Done: done,
75-
RetryTimeDuration: time.Duration(3 * time.Second),
76-
FuncGenerator: testGenerateFunc,
74+
return
75+
}
76+
for i := 0; i < 10; i++ {
77+
id := fmt.Sprintf("task_%v", i)
78+
meta := &model.TaskMeta{
79+
MetaId: id,
7780
}
78-
tsk := scheduler.NewTaskScheduler(tconf)
79-
postgClient := dbStruct{}
80-
tsk.InitScheduler(postgClient)
81-
if err != nil {
82-
return
81+
if id == "task_6" {
82+
meta.Retry = 5
8383
}
84-
for i := 0; i < 10; i++ {
85-
id := fmt.Sprintf("task_%v", i)
86-
meta := &model.TaskMeta{
87-
MetaId: id,
88-
}
89-
if id == "task_6" {
90-
meta.Retry = 5
91-
}
92-
mdlTsk := model.Task{
93-
Meta: meta,
94-
}
95-
err := tsk.AddNewTask(mdlTsk)
96-
if err == nil {
97-
wg.Add(1)
98-
}
84+
mdlTsk := model.Task{
85+
Meta: meta,
86+
}
87+
err := tsk.AddNewTask(mdlTsk)
88+
if err == nil {
89+
wg.Add(1)
9990
}
10091
}
92+
10193
wg.Wait()
10294
if successC == 9 && failC == 1 {
10395
t.Log("successfully completed the tasks")

manager/task-manager.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,17 @@ import (
1010
)
1111

1212
type TaskManager struct {
13-
postgClient util.PostgClient
13+
storageClient util.StorageClient
1414
taskActor *TaskActor
1515
done chan int
1616
priorityQueue PriorityQueue
1717
retryTimeDuration time.Duration
1818
funcGenerator func() func(*model.TaskMeta) error
1919
}
2020

21-
func InitManager(postgClient util.PostgClient, taskActor *TaskActor, retryTime time.Duration, funcGenerator func() func(*model.TaskMeta) error, done chan int) *TaskManager {
21+
func InitManager(storageClient util.StorageClient, taskActor *TaskActor, retryTime time.Duration, funcGenerator func() func(*model.TaskMeta) error, done chan int) *TaskManager {
2222
return &TaskManager{
23-
postgClient: postgClient,
23+
storageClient: storageClient,
2424
taskActor: taskActor,
2525
funcGenerator: funcGenerator,
2626
retryTimeDuration: retryTime,
@@ -40,7 +40,7 @@ func (tm *TaskManager) AddNewTask(task model.Task) error {
4040
if task.Meta.Delay > 0 {
4141
task.Meta.ExecutionTime = time.Now().Unix() + int64(task.Meta.Delay)*60
4242
}
43-
id, err := tm.postgClient.SaveTask(task.Meta)
43+
id, err := tm.storageClient.SaveTask(task.Meta)
4444
if err != nil {
4545
fmt.Printf("failed to save the task %v\n", err)
4646
return err
@@ -70,7 +70,7 @@ func (tm *TaskManager) assignTask(idTask string, meta *model.TaskMeta) {
7070
taskStatus = util.JOB_DETAIL_STATUS_FAILED
7171
}
7272
}
73-
tm.postgClient.UpdateTaskStatus(idTask, taskStatus, *meta)
73+
tm.storageClient.UpdateTaskStatus(idTask, taskStatus, *meta)
7474
}
7575
tsk := model.ActorTask{
7676
Meta: meta,
@@ -108,7 +108,7 @@ func (tm *TaskManager) retryFailedTask() {
108108
ticker.Stop()
109109
return
110110
case <-ticker.C:
111-
tsks, err := tm.postgClient.GetFailTask()
111+
tsks, err := tm.storageClient.GetFailTask()
112112
if err == nil {
113113
for _, tsk := range tsks {
114114
go tm.assignTask(tsk.Id, tsk.Meta)
@@ -121,7 +121,7 @@ func (tm *TaskManager) retryFailedTask() {
121121
}
122122

123123
func (tm *TaskManager) loadPendingTask() {
124-
tsks, err := tm.postgClient.GetPendingTask()
124+
tsks, err := tm.storageClient.GetPendingTask()
125125
if err == nil {
126126
for _, tsk := range tsks {
127127
go tm.assignTask(tsk.Id, tsk.Meta)

scheduler/TaskSchedulerConfig.go

Lines changed: 2 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,14 @@
11
package scheduler
22

33
import (
4-
"fmt"
54
"time"
65

76
manager "github.com/amitiwary999/task-scheduler/manager"
87
model "github.com/amitiwary999/task-scheduler/model"
9-
storage "github.com/amitiwary999/task-scheduler/storage"
108
"github.com/amitiwary999/task-scheduler/util"
119
)
1210

1311
type TaskConfig struct {
14-
PostgUrl string
15-
PoolLimit int16
16-
JobTableName string
1712
MaxTaskWorker uint16
1813
TaskQueueSize uint16
1914
RetryTimeDuration time.Duration
@@ -22,11 +17,8 @@ type TaskConfig struct {
2217
}
2318

2419
type TaskScheduler struct {
25-
postgUrl string
26-
poolLimit int16
2720
maxTaskWorker uint16
2821
taskQueueSize uint16
29-
jobTableName string
3022
retryTimeDuration time.Duration
3123
funcGenerator func() func(*model.TaskMeta) error
3224
done chan int
@@ -36,33 +28,16 @@ type TaskScheduler struct {
3628
func NewTaskScheduler(tconf *TaskConfig) *TaskScheduler {
3729
return &TaskScheduler{
3830
done: tconf.Done,
39-
postgUrl: tconf.PostgUrl,
40-
poolLimit: tconf.PoolLimit,
4131
maxTaskWorker: tconf.MaxTaskWorker,
4232
taskQueueSize: tconf.TaskQueueSize,
43-
jobTableName: tconf.JobTableName,
4433
funcGenerator: tconf.FuncGenerator,
4534
retryTimeDuration: tconf.RetryTimeDuration,
4635
}
4736
}
4837

49-
func (t *TaskScheduler) InitStorage() (util.PostgClient, error) {
50-
postgClient, error := storage.NewPostgresClient(t.postgUrl, t.poolLimit, t.jobTableName)
51-
if error != nil {
52-
fmt.Printf("postgres cient failed %v\n", error)
53-
return nil, error
54-
}
55-
err := postgClient.CreateJobTable()
56-
if err != nil {
57-
fmt.Printf("failed to create the table to save job details %v \n", err)
58-
return nil, err
59-
}
60-
return postgClient, nil
61-
}
62-
63-
func (t *TaskScheduler) InitScheduler(postgClient util.PostgClient) {
38+
func (t *TaskScheduler) InitScheduler(storageClient util.StorageClient) {
6439
ta := manager.NewTaskActor(t.maxTaskWorker, t.done, t.taskQueueSize)
65-
taskM := manager.InitManager(postgClient, ta, t.retryTimeDuration, t.funcGenerator, t.done)
40+
taskM := manager.InitManager(storageClient, ta, t.retryTimeDuration, t.funcGenerator, t.done)
6641
t.taskM = taskM
6742
taskM.StartManager()
6843
}

util/type.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ type SupabaseClient interface {
2323
GetPendingTask() ([]byte, error)
2424
}
2525

26-
type PostgClient interface {
26+
type StorageClient interface {
2727
SaveTask(meta *model.TaskMeta) (string, error)
2828
UpdateTaskStatus(id, status string, meta model.TaskMeta) error
2929
GetPendingTask() ([]model.PendingTask, error)

0 commit comments

Comments
 (0)