利用Go語(yǔ)言快速實(shí)現(xiàn)一個(gè)極簡(jiǎn)任務(wù)調(diào)度系統(tǒng)
引子
任務(wù)調(diào)度(Task Scheduling)是很多軟件系統(tǒng)中的重要組成部分,字面上的意思是按照一定要求分配運(yùn)行一些通常時(shí)間較長(zhǎng)的腳本或程序。在爬蟲(chóng)管理平臺(tái) Crawlab 中,任務(wù)調(diào)度是其中的核心模塊,相信不少朋友會(huì)好奇如何編寫(xiě)一個(gè)任務(wù)調(diào)度系統(tǒng)。本篇文章會(huì)教讀者用 Go 語(yǔ)言編寫(xiě)一個(gè)非常簡(jiǎn)單的任務(wù)調(diào)度系統(tǒng)。
思路
我們首先理清一下思路,開(kāi)發(fā)最小化任務(wù)調(diào)度器需要什么。
- 交互界面(API)
- 定時(shí)任務(wù)(Cron)
- 任務(wù)執(zhí)行(Execute Tasks)
整個(gè)流程如下:
我們通過(guò) API 創(chuàng)建定時(shí)任務(wù),執(zhí)行器根據(jù)定時(shí)任務(wù)標(biāo)準(zhǔn)定期執(zhí)行腳本。
實(shí)戰(zhàn)
交互界面
首先我們來(lái)搭個(gè)架子。在項(xiàng)目目錄下創(chuàng)建一個(gè) main.go
文件,并輸入以下內(nèi)容。其中 gin
是非常流行的 Go 語(yǔ)言 API 引擎。
package main ? import ( "fmt" "github.com/gin-gonic/gin" "os" ) ? func main() { // api engine app := gin.New() ? // api routes app.GET("/jobs", GetJobs) app.POST("/jobs", AddJob) app.DELETE("/jobs", DeleteJob) ? // run api on port 9092 if err := app.Run(":9092"); err != nil { _, err = fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
然后添加 api.go
文件,輸入以下內(nèi)容,注意,這里沒(méi)有任何代碼實(shí)現(xiàn),只是加入了占位區(qū)域。
package main ? import "github.com/gin-gonic/gin" ? func GetJobs(c *gin.Context) { // TODO: implementation here } ? func AddJob(c *gin.Context) { // TODO: implementation here } ? func DeleteJob(c *gin.Context) { // TODO: implementation here }
定時(shí)任務(wù)
然后是任務(wù)調(diào)度的核心,定時(shí)任務(wù)。這里我們使用 robfig/cron,Go 語(yǔ)言比較流行的定時(shí)任務(wù)庫(kù)。
現(xiàn)在創(chuàng)建 cron.go
文件,輸入以下內(nèi)容。其中 Cron
就是 robfig/cron
庫(kù)中的 Cron
類(lèi)生成的實(shí)例。
package main ? import "github.com/robfig/cron" ? func init() { // start to run Cron.Run() } ? // Cron create a new cron.Cron instance var Cron = cron.New()
現(xiàn)在創(chuàng)建好了主要定時(shí)任務(wù)實(shí)例,就可以將核心邏輯添加在剛才的 API 占位區(qū)域了。
同樣是 api.go
,將核心代碼添加進(jìn)來(lái)。
package main ? import ( "github.com/gin-gonic/gin" "github.com/robfig/cron/v3" "net/http" "strconv" ) ? func GetJobs(c *gin.Context) { // return a list of cron job entries var results []map[string]interface{} for _, e := range Cron.Entries() { results = append(results, map[string]interface{}{ "id": e.ID, "next": e.Next, }) } c.JSON(http.StatusOK, Cron.Entries()) } ? func AddJob(c *gin.Context) { // post JSON payload var payload struct { Cron string `json:"cron"` Exec string `json:"exec"` } if err := c.ShouldBindJSON(&payload); err != nil { c.AbortWithStatus(http.StatusBadRequest) return } ? // add cron job eid, err := Cron.AddFunc(payload.Cron, func() { // TODO: implementation here }) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, map[string]interface{}{ "error": err.Error(), }) return } ? c.AbortWithStatusJSON(http.StatusOK, map[string]interface{}{ "id": eid, }) } ? func DeleteJob(c *gin.Context) { // cron job entry id id := c.Param("id") eid, err := strconv.Atoi(id) if err != nil { c.AbortWithStatus(http.StatusBadRequest) return } ? // remove cron job Cron.Remove(cron.EntryID(eid)) ? c.AbortWithStatus(http.StatusOK) }
在這段代碼中,我們實(shí)現(xiàn)了大部分邏輯,只在 AddJob
的 Cron.AddFunc
中第二個(gè)參數(shù)里,剩下最后一部分執(zhí)行任務(wù)的代碼。下面將來(lái)實(shí)現(xiàn)一下。
任務(wù)執(zhí)行
現(xiàn)在需要添加任務(wù)執(zhí)行的代碼邏輯,咱們創(chuàng)建 exec.go
文件,輸入以下內(nèi)容。這里我們用到了 Go 語(yǔ)言?xún)?nèi)置的 shell 運(yùn)行管理庫(kù) os/exec
,可以執(zhí)行任何 shell 命令。
package main ? import ( "fmt" "os" "os/exec" "strings" ) ? func ExecuteTask(execCmd string) { // execute command string parts, delimited by space execParts := strings.Split(execCmd, " ") ? // executable name execName := execParts[0] ? // execute command parameters execParams := strings.Join(execParts[1:], " ") ? // execute command instance cmd := exec.Command(execName, execParams) ? // run execute command instance if err := cmd.Run(); err != nil { _, err = fmt.Fprintln(os.Stderr, err) fmt.Println(err.Error()) } }
好了,現(xiàn)在我們將這部分執(zhí)行代碼邏輯放到之前的占位區(qū)域中。
... // add cron job eid, _ := Cron.AddFunc(payload.Cron, func() { ExecuteTask(payload.Exec) }) ...
代碼效果
OK,大功告成!現(xiàn)在我們可以試試運(yùn)行這個(gè)極簡(jiǎn)的任務(wù)調(diào)度器了。
在命令行中敲入 go run .
,API 引擎就啟動(dòng)起來(lái)了。
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) ? [GIN-debug] GET /jobs --> main.GetJobs (1 handlers) [GIN-debug] POST /jobs --> main.AddJob (1 handlers) [GIN-debug] DELETE /jobs/:id --> main.DeleteJob (1 handlers) [GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value. Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details. [GIN-debug] Listening and serving HTTP on :9092
現(xiàn)在打開(kāi)另一個(gè)命令行窗口,輸入 curl -X POST -d '{"cron":"* * * * *","exec":"touch /tmp/hello.txt"}' http://localhost:9092/jobs
,會(huì)得到如下返回結(jié)果。表示已經(jīng)生成了相應(yīng)的定時(shí)任務(wù),任務(wù) ID 為 1,每分鐘跑一次,會(huì)更新一次 /tmp/hello.txt
。
{"id":1}
在這個(gè)命令行窗口中輸入 curl http://localhost:9092/jobs
。
[{"id":1,"next":"2022-10-03T12:46:00+08:00"}]
這表示下一次執(zhí)行是 1 分鐘之后。
等待一分鐘,執(zhí)行 ls -l /tmp/hello.txt
,得到如下結(jié)果。
-rw-r--r-- 1 marvzhang wheel 0B Oct 3 12:46 /tmp/hello.txt
也就是說(shuō),執(zhí)行成功了,大功告成!
總結(jié)
本篇文章通過(guò)將 Go 語(yǔ)言幾個(gè)庫(kù)簡(jiǎn)單組合,就開(kāi)發(fā)出了一個(gè)極簡(jiǎn)的任務(wù)調(diào)度系統(tǒng)。所用到的核心庫(kù):
- gin
- robfig/cron
- os/exec
整個(gè)代碼示例倉(cāng)庫(kù)在 GitHub 上: https://github.com/tikazyq/codao-code/tree/main/2022-10/go-task-scheduler
到此這篇關(guān)于利用Go語(yǔ)言快速實(shí)現(xiàn)一個(gè)極簡(jiǎn)任務(wù)調(diào)度系統(tǒng)的文章就介紹到這了,更多相關(guān)Go語(yǔ)言實(shí)現(xiàn)任務(wù)調(diào)度系統(tǒng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
線(xiàn)上golang grpc服務(wù)資源泄露問(wèn)題排查
這篇文章主要介紹了線(xiàn)上golang grpc服務(wù)資源泄露問(wèn)題排查,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12web項(xiàng)目中g(shù)olang性能監(jiān)控解析
這篇文章主要為大家介紹了web項(xiàng)目中g(shù)olang性能監(jiān)控詳細(xì)的解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-04-04Go語(yǔ)言實(shí)現(xiàn)請(qǐng)求超時(shí)處理的方法總結(jié)
這篇文章主要為大家詳細(xì)介紹了Go語(yǔ)言中實(shí)現(xiàn)請(qǐng)求的超時(shí)控制的方法,主要是通過(guò)timer和timerCtx來(lái)實(shí)現(xiàn)請(qǐng)求的超時(shí)控制,希望對(duì)大家有所幫助2023-05-05Go語(yǔ)言狀態(tài)機(jī)的實(shí)現(xiàn)
本文主要介紹了Go語(yǔ)言狀態(tài)機(jī)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03golang?http請(qǐng)求未釋放造成的錯(cuò)誤問(wèn)題
這篇文章主要介紹了golang?http請(qǐng)求未釋放造成的錯(cuò)誤問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01Go Uber靜態(tài)分析工具NilAway使用初體驗(yàn)
這篇文章主要介紹了Go Uber靜態(tài)分析工具NilAway使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01