MCPcopy Create free account
hub / github.com/astercloud/aster / EveryInterval

Method EveryInterval

pkg/core/scheduler.go:209–261  ·  view source on GitHub ↗

EveryInterval 每隔一段时间执行

(interval time.Duration, callback TaskCallback)

Source from the content-addressed store, hash-verified

207
208// EveryInterval 每隔一段时间执行
209func (s *Scheduler) EveryInterval(interval time.Duration, callback TaskCallback) (string, error) {
210 if interval <= 0 {
211 return "", fmt.Errorf("interval must be positive, got %v", interval)
212 }
213
214 s.mu.Lock()
215 defer s.mu.Unlock()
216
217 id := generateTaskID("interval")
218 ticker := time.NewTicker(interval)
219 stopCh := make(chan struct{})
220
221 task := &IntervalTask{
222 ID: id,
223 Interval: interval,
224 Callback: callback,
225 ticker: ticker,
226 stopCh: stopCh,
227 }
228
229 s.intervalTasks[id] = task
230
231 // 启动定时器
232 s.wg.Add(1)
233 go func() {
234 defer s.wg.Done()
235
236 for {
237 select {
238 case <-ticker.C:
239 // 执行回调
240 if err := callback(s.ctx); err != nil {
241 schedulerLog.Warn(s.ctx, "interval task callback error", map[string]any{"task_id": id, "error": err})
242 }
243
244 // 通知触发
245 if s.opts.OnTrigger != nil {
246 s.opts.OnTrigger(id, fmt.Sprintf("interval:%v", interval), TriggerKindInterval)
247 }
248
249 case <-stopCh:
250 ticker.Stop()
251 return
252
253 case <-s.ctx.Done():
254 ticker.Stop()
255 return
256 }
257 }
258 }()
259
260 return id, nil
261}
262
263// Schedule 使用调度规格创建任务
264func (s *Scheduler) Schedule(spec string, callback TaskCallback) (string, error) {

Callers 10

ScheduleMethod · 0.95
TestScheduler_ClearFunction · 0.95
TestScheduler_ShutdownFunction · 0.95
demonstrateMultipleTasksFunction · 0.95

Calls 4

generateTaskIDFunction · 0.70
AddMethod · 0.65
WarnMethod · 0.65
StopMethod · 0.65

Tested by 5

TestScheduler_ClearFunction · 0.76
TestScheduler_ShutdownFunction · 0.76