dingdayu-go-asyncGo 安全异步任务

联合创作 · 2023-09-29 07:08

Go 安全异步任务

基于 Go 的安全异步包。

安装

go get github.com/dingdayu/async/v2

示例

package main

import (
 "context"
 "fmt"
 "os"
 "os/signal"
 "sync"
 "syscall"
 "time"

 "github.com/dingdayu/async/v2"
)

type ExampleAsync struct {
}

// OnPreRun: 运行之前的调用, panic 会导致注册失败
func (a ExampleAsync) OnPreRun() {
 fmt.Printf("\u001B[1;30;42m[info]\u001B[0m ExampleAsync 注册成功,开始运行!\n")
}

// Name: 异步任务的名称,需要在进程内唯一,否则会被替换
func (a ExampleAsync) Name() string {
 return "example"
}

// Handle: 异步任务的核心逻辑,通过 for 进行巡航,通过 context 进行安全退出
func (a ExampleAsync) Handle(ctx context.Context, wg *sync.WaitGroup) {
 defer wg.Done()

 for {
  select {
  default:
   // todo:: Logical unit
   time.Sleep(3 * time.Second)
   fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
  case <-ctx.Done():
   return
  }
 }
}

// OnShutdown: 在退出前并行调用
func (a ExampleAsync) OnShutdown(s os.Signal) {
 fmt.Printf("\u001B[1;30;42m[info]\u001B[0m ExampleAsync 接收到系统信号[%s],准备退出!\n", s.String())
}

func main() {
 // 处理系统 SIGINT and SIGTERM 信号.
 ch := make(chan os.Signal)
 signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)

 ayc := async.NewAsync(context.Background(), ch)

 _ = ayc.Register(ExampleAsync{})

 ayc.Wait()
 fmt.Println("[1;30;42m[info]\u001B[0m Task exited")
}
浏览 6
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报