Files

80 lines
1.3 KiB
Go
Raw Permalink Normal View History

2025-03-20 22:27:37 +08:00
package task
import (
2025-06-12 23:38:23 +08:00
"context"
"sync"
2024-09-27 22:01:48 +08:00
"time"
"github.com/v03413/bepusdt/app/model"
)
// 区块扫描队列最大长度,避免可能因为 Rpc Rate Limit 问题导致消费队列堆积,进而导致OOM,暂时简单限制队列长度
// 如果直接使用固定长度的 Channel 控制,会导致区块高度同步时也彻底阻塞,无法对外界输出日志导致无法观察,彻底垮掉
// 如果确实是因为 Rate Limit 问题导致的异常,优先考虑的是提升 Rpc 节点的质量和稳定性
const blockQueueLimit = 100
2025-10-13 11:27:38 +08:00
type Task struct {
Duration time.Duration
Callback func(ctx context.Context)
2024-09-27 22:01:48 +08:00
}
2025-06-12 23:38:23 +08:00
var (
2025-10-13 11:27:38 +08:00
tasks []Task
2025-06-12 23:38:23 +08:00
mu sync.Mutex
)
2024-09-27 22:01:48 +08:00
2025-06-17 15:01:13 +08:00
func Init() error {
model.RefreshC()
2025-06-15 21:57:46 +08:00
bscInit()
ethInit()
plasmaInit()
2025-06-15 21:57:46 +08:00
polygonInit()
2025-07-26 01:25:48 +08:00
arbitrumInit()
2025-06-15 21:57:46 +08:00
xlayerInit()
2025-08-11 17:34:52 +08:00
baseInit()
2025-06-17 15:01:13 +08:00
return nil
2025-06-15 21:57:46 +08:00
}
2025-10-13 11:27:38 +08:00
func Register(t Task) {
2025-06-12 23:38:23 +08:00
mu.Lock()
defer mu.Unlock()
2024-09-27 22:01:48 +08:00
2025-10-13 11:27:38 +08:00
if t.Callback == nil {
2025-06-12 23:38:23 +08:00
2025-10-13 11:27:38 +08:00
panic("Task Callback cannot be nil")
2025-06-12 23:38:23 +08:00
}
tasks = append(tasks, t)
2024-09-27 22:01:48 +08:00
}
2025-08-14 16:56:09 +08:00
func Start(ctx context.Context) {
2025-06-12 23:38:23 +08:00
mu.Lock()
defer mu.Unlock()
for _, t := range tasks {
2025-10-13 11:27:38 +08:00
go func(t Task) {
if t.Duration <= 0 {
t.Callback(ctx)
2025-06-12 23:38:23 +08:00
return
}
2025-10-13 11:27:38 +08:00
t.Callback(ctx)
2025-06-12 23:38:23 +08:00
2025-10-13 11:27:38 +08:00
ticker := time.NewTicker(t.Duration)
2025-06-12 23:38:23 +08:00
defer ticker.Stop()
for {
select {
2025-08-14 16:56:09 +08:00
case <-ctx.Done():
2025-06-12 23:38:23 +08:00
return
case <-ticker.C:
2025-10-13 11:27:38 +08:00
t.Callback(ctx)
2025-06-12 23:38:23 +08:00
}
}
}(t)
}
}