SoFunction
Updated on 2025-03-05

Example code of lightweight asynchronous task distributor based on golang channel implementation

Preface

Sometimes, in order to better utilize computer resources, we can queue up and execute some time-consuming tasks asynchronously. Let me give you a simple example in life. In most restaurants, you will find a place to order food first. After reading the menu, you will find a waiter to order food. Then wait for the food to be prepared and delivered. The restaurant kitchen here is the underlying resource of the computer, the dishes are the tasks to be performed, and the waiter is our go channel.

There are many useful frameworks about message queues, such as nsq, nats, kafka, etc. But sometimes we only need lightweight asynchronous task tools, and not too "complex" frameworks relative to our needs. So we learned from some project frameworks and made a small package.

Project address:/chenhg5/go...  (Local download

The use of go-task is very simple. You only need to initialize a task processor, then add tasks to the processor, and the processor will execute asynchronously.

Take an example of a restaurant, the code is as follows:

package main

import (
 "runtime"
 "fmt"
 "time"
 "/chenhg5/go-task"
)

func main() {

 // init
 (())

 // Ten people ordered the dishes at the same time for i := 0; i < 10; i++ {
  ((
   map[string]interface{}{
    "paramA" : "value",
   }, // Parameters   []{ordering, cooking, deliverying}, // Task list   -1), // -1 means that the task does not expire  )
 }

 ( * 50)
}

// Order taskfunc ordering(uuid string, param map[string]interface{}) (string, error) {
 ("i am ordering")
 ( * 1)
 return uuid, nil
}

// Cooking tasksfunc cooking(uuid string, param map[string]interface{}) (string, error) {
 ("i am cooking")
 ( * 1)
 return uuid, nil
}

// Delivery tasksfunc deliverying(uuid string, param map[string]interface{}) (string, error) {
 ("i am deliverying")
 ( * 1)
 return uuid, nil
}

Run it once and you will see:

i am ordering
i am ordering
i am ordering
i am ordering
i am ordering
i am ordering
i am ordering
i am ordering
i am cooking
i am cooking
i am cooking
i am cooking
i am cooking
i am cooking
i am cooking
i am cooking
i am deliverying
i am deliverying
i am deliverying
i am deliverying
i am deliverying
i am deliverying
i am deliverying
i am deliverying
i am ordering
i am ordering
i am cooking
i am cooking
i am deliverying
i am deliverying

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.