任务调度demo

  • 模拟任务调度
  • 同步(串行)任务/异步(并行)任务
  • 遇到同步任务需执行完成后再执行后续任务
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
package main

import (
"context"
"fmt"
"sync"
"time"
)

func test(wg *sync.WaitGroup, ctx context.Context, jobId int) {
defer wg.Done()
for i := 0; i < 5; i++ {
select {
case <-ctx.Done():
fmt.Printf("任务Id:%d,异常退出\n", jobId)
return
default:
fmt.Printf("任务Id:%d,执行第%d次\n", jobId, i)
if jobId > 2 {
time.Sleep(time.Second * 5)
} else {
time.Sleep(time.Second * 2)
}

}
}
}

func main() {
ctx, cancel := context.WithCancel(context.Background())
wg := new(sync.WaitGroup)
go func() {
time.Sleep(time.Second * 20)
cancel()
}()
for i := 0; i < 5; i++ {
wg.Add(1)
go test(wg, ctx, i)

if i < 1 {
wg.Wait()
select {
case <-ctx.Done():
fmt.Println("main1 异常退出")
return
default:
fmt.Println("1 select")
}
}
}
wg.Wait()
select {
case <-ctx.Done():
fmt.Println("main2 异常退出")
return
default:
fmt.Println("2 select")
}
//测试阻塞
select {}
}