context取消任务demo

一个基于 gin 的demo ,支持

创建任务,

停止(取消)任务 -》基于 context cancle,

查询任务

传递任务id  基于 context value

 

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
 
import (
    "fmt"
    "math/rand"
    "strconv"
 
    "context"
    "time"
 
    "github.com/gin-gonic/gin"
)
 
type ReqTask struct {
    TaskID string
}
 
type Task struct {
    status string
    cancel context.CancelFunc
}
 
func generate_taskid() int {
    rand.Seed(time.Now().UnixNano())
    return rand.Intn(100000)
 
}
 
func runtask(ctx context.Context) {
    var tmptaskid interface{}
    if tmptaskid = ctx.Value("TASKID"); tmptaskid != nil {
        fmt.Println("found value:", tmptaskid)
    }
    var taskid = fmt.Sprintf("%v", tmptaskid)
    fmt.Println(taskid)
 
    for {
        select {
        default:
            fmt.Printf("Task %s is running \n", taskid)
            time.Sleep(time.Duration(1) * time.Second)
        case <-ctx.Done():
            fmt.Printf("Task %s is stoped \n", taskid)
            return
        }
    }
}
 
func main() {
    r := gin.Default()
    alltaskinfo := make(map[string]*Task)
 
    r.POST("/startask", func(c *gin.Context) {
        var (
            task Task
            ctx  context.Context
        )
        taskid := strconv.Itoa(generate_taskid())
        task.status = "running"
        ctx, task.cancel = context.WithCancel(context.Background())
        ctx = context.WithValue(ctx, "TASKID", taskid)
 
        alltaskinfo[taskid] = &task
        go runtask(ctx)
        c.JSON(200, gin.H{
            "message": "task " + taskid + " started",
        })
        return
    })
 
    r.POST("/querytask", func(c *gin.Context) {
        var req ReqTask
        if err := c.ShouldBind(&req); err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }
        taskid := req.TaskID
        task, ok := alltaskinfo[taskid]
        if ok {
            c.JSON(200, gin.H{
                "message": "task " + taskid + " status is " + task.status,
            })
        } else {
            c.JSON(404, gin.H{
                "message": "task " + taskid + " not found",
            })
        }
    })
 
    r.POST("/stoptask", func(c *gin.Context) {
        var req ReqTask
        if err := c.ShouldBind(&req); err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }
        taskid := req.TaskID
        task, ok := alltaskinfo[taskid]
        if ok {
            task.cancel()
            task.status = "stoped"
            c.JSON(200, gin.H{
                "message": "task " + taskid + " stoped",
            })
        } else {
            c.JSON(404, gin.H{
                "message": "task " + taskid + " not found",
            })
        }
 
    })
 
    r.Run(":8081") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

  


import ("fmt""math/rand""strconv"
"context""time"
"github.com/gin-gonic/gin")
type ReqTask struct {TaskID string}
type Task struct {status stringcancel context.CancelFunc}
func generate_taskid() int {rand.Seed(time.Now().UnixNano())return rand.Intn(100000)
}
func runtask(ctx context.Context) {var tmptaskid interface{}if tmptaskid = ctx.Value("TASKID"); tmptaskid != nil {fmt.Println("found value:", tmptaskid)}var taskid = fmt.Sprintf("%v", tmptaskid)fmt.Println(taskid)
for {select {default:fmt.Printf("Task %s is running \n", taskid)time.Sleep(time.Duration(1) * time.Second)case <-ctx.Done():fmt.Printf("Task %s is stoped \n", taskid)return}}}
func main() {r := gin.Default()alltaskinfo := make(map[string]*Task)
r.POST("/startask", func(c *gin.Context) {var (task Taskctx  context.Context)taskid := strconv.Itoa(generate_taskid())task.status = "running"ctx, task.cancel = context.WithCancel(context.Background())ctx = context.WithValue(ctx, "TASKID", taskid)
alltaskinfo[taskid] = &taskgo runtask(ctx)c.JSON(200, gin.H{"message": "task " + taskid + " started",})return})
r.POST("/querytask", func(c *gin.Context) {var req ReqTaskif err := c.ShouldBind(&req); err != nil {c.JSON(500, gin.H{"error": err.Error()})return}taskid := req.TaskIDtask, ok := alltaskinfo[taskid]if ok {c.JSON(200, gin.H{"message": "task " + taskid + " status is " + task.status,})} else {c.JSON(404, gin.H{"message": "task " + taskid + " not found",})}})
r.POST("/stoptask", func(c *gin.Context) {var req ReqTaskif err := c.ShouldBind(&req); err != nil {c.JSON(500, gin.H{"error": err.Error()})return}taskid := req.TaskIDtask, ok := alltaskinfo[taskid]if ok {task.cancel()task.status = "stoped"c.JSON(200, gin.H{"message": "task " + taskid + " stoped",})} else {c.JSON(404, gin.H{"message": "task " + taskid + " not found",})}
})
r.Run(":8081") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")}
 

posted on   思此狂  阅读(138)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2017-07-10 express-cookie

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示