[feat] 新增package defertaskthread,用于执行延时任务

pull/2/head v0.15.4
q191201771 4 years ago
parent 67d32aba74
commit 6904ae65a5

@ -64,6 +64,9 @@ type Connection interface {
ModReadTimeoutMS(n int)
ModWriteTimeoutMS(n int)
// 连接上读取和发送的字节总数。
// 注意如果是异步发送发送字节统计的是调用底层write的值而非上层调用Connection发送的值
// 也即不包含Connection中的发送缓存部分但是可能包含内核socket发送缓冲区的值。
GetStat() Stat
}

@ -0,0 +1,21 @@
// Copyright 2020, Chef. All rights reserved.
// https://github.com/q191201771/naza
//
// Use of this source code is governed by a MIT-style license
// that can be found in the License file.
//
// Author: Chef (191201771@qq.com)
package defertaskthread
import "time"
type deferTaskThread struct {
}
func (d *deferTaskThread) Go(deferMS int, task TaskFn, param ...interface{}) {
go func() {
time.Sleep(time.Duration(deferMS) * time.Millisecond)
task(param...)
}()
}

@ -0,0 +1,29 @@
// Copyright 2020, Chef. All rights reserved.
// https://github.com/q191201771/naza
//
// Use of this source code is governed by a MIT-style license
// that can be found in the License file.
//
// Author: Chef (191201771@qq.com)
package defertaskthread_test
import (
"testing"
"time"
"github.com/q191201771/naza/pkg/nazalog"
"github.com/q191201771/naza/pkg/defertaskthread"
)
func TestDeferTaskThread(t *testing.T) {
d := defertaskthread.NewDeferTaskThread()
for i := 0; i < 300; i += 50 {
d.Go(i, func(param ...interface{}) {
ii := param[0].(int)
nazalog.Debugf("running %d", ii)
}, i)
}
time.Sleep(300 * time.Millisecond)
}

@ -0,0 +1,19 @@
// Copyright 2020, Chef. All rights reserved.
// https://github.com/q191201771/naza
//
// Use of this source code is governed by a MIT-style license
// that can be found in the License file.
//
// Author: Chef (191201771@qq.com)
package defertaskthread
var thread DeferTaskThread
func Go(deferMS int, task TaskFn, param ...interface{}) {
thread.Go(deferMS, task, param...)
}
func init() {
thread = NewDeferTaskThread()
}

@ -0,0 +1,21 @@
// Copyright 2020, Chef. All rights reserved.
// https://github.com/q191201771/naza
//
// Use of this source code is governed by a MIT-style license
// that can be found in the License file.
//
// Author: Chef (191201771@qq.com)
package defertaskthread
type TaskFn func(param ...interface{})
type DeferTaskThread interface {
// 注意一个thread的多个task本应该是串行执行的语义
// 目前为了简单,让它们并行执行了,以后可能会发生变化
Go(deferMS int, task TaskFn, param ...interface{})
}
func NewDeferTaskThread() DeferTaskThread {
return &deferTaskThread{}
}
Loading…
Cancel
Save