|
| 1 | +--- |
| 2 | +weight: 202 |
| 3 | +title: "暂停、继续和取消" |
| 4 | +description: "关于如何暂停、继续和取消 pipeline" |
| 5 | +icon: "article" |
| 6 | +date: "2025-04-20T15:22:48+08:00" |
| 7 | +lastmod: "2025-04-20T15:22:48+08:00" |
| 8 | +draft: false |
| 9 | +toc: true |
| 10 | +--- |
| 11 | + |
| 12 | +## 示例 |
| 13 | + |
| 14 | +OGraph Pipeline 支持暂停运行、继续运行和取消运行,示例代码如下: |
| 15 | + |
| 16 | +```go |
| 17 | + pipeline := ograph.NewPipeline() |
| 18 | + |
| 19 | + var startTime time.Time |
| 20 | + |
| 21 | + a := ograph.NewElement("a").UseFn(func() error { |
| 22 | + fmt.Println("a running") |
| 23 | + startTime = time.Now() |
| 24 | + time.Sleep(time.Second) |
| 25 | + return nil |
| 26 | + }) |
| 27 | + |
| 28 | + b := ograph.NewElement("b").UseFn(func() error { |
| 29 | + fmt.Println("b running, after", time.Since(startTime)) |
| 30 | + time.Sleep(time.Second) |
| 31 | + return nil |
| 32 | + }) |
| 33 | + |
| 34 | + c := ograph.NewElement("c").UseFn(func() error { |
| 35 | + fmt.Println("c running, after", time.Since(startTime)) |
| 36 | + return nil |
| 37 | + }) |
| 38 | + |
| 39 | + pipeline.Register(a).Register(b, ograph.Rely(a)).Register(c, ograph.Rely(b)) |
| 40 | + |
| 41 | + ctx, cancel := context.WithCancel(context.Background()) |
| 42 | + |
| 43 | + pause, continueRun, wait := pipeline.AsyncRun(ctx, nil) |
| 44 | + |
| 45 | + time.Sleep(time.Millisecond * 500) |
| 46 | + |
| 47 | + pause() // pause before run node b |
| 48 | + |
| 49 | + time.Sleep(time.Second) |
| 50 | + |
| 51 | + continueRun() // b continue run, after 1.5s (0.5+1), not 1s |
| 52 | + |
| 53 | + time.Sleep(time.Millisecond * 500) |
| 54 | + |
| 55 | + cancel() // cancel before run node c, so node c will never be ran |
| 56 | + |
| 57 | + err := wait() // wait pipeline finish |
| 58 | + |
| 59 | + fmt.Println(err) // should get context canceled err |
| 60 | +``` |
| 61 | + |
| 62 | +## 流程图 |
| 63 | + |
| 64 | +示例代码运行过程如下: |
| 65 | + |
| 66 | +```mermaid |
| 67 | +%%{init: { 'logLevel': 'debug', 'theme': 'default', 'timeline': {'disableMulticolor': true} } }%% |
| 68 | +timeline |
| 69 | + title Execution process |
| 70 | + 0s~0.5s : Node a running |
| 71 | + 0.5s~1s : Node a finish |
| 72 | + : Pipeline pause |
| 73 | + 1s~1.5s : Pipeline pause |
| 74 | + 1.5s~2s : Pipeline continue : Node b running |
| 75 | + 2s~2.5s : Node b finish : Pipeline cancel |
| 76 | +
|
| 77 | +``` |
| 78 | + |
| 79 | +{{< alert context="info" text="暂停不会影响正在运行中的节点。如果节点本身不支持取消,那么取消也不会影响运行中的节点。" />}} |
0 commit comments