├── .gitignore ├── LICENSE ├── README.md ├── client ├── client.go └── client_web │ ├── index.html │ └── load_as_raw.go ├── cmd └── crontable-web │ └── main.go ├── crontab.go ├── example ├── cron.go ├── demo.jpeg └── manager.go ├── go.mod ├── task_manager.go ├── tm_options.go └── tm_task.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | *.log 17 | *.sum 18 | *.DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # crontab 2 | a simple and powerful crontab written in golang with web page management 3 | golang实现的简单便捷的计划任务管理系统, 自带 web 界面,方便的管理多个任务 4 | 支持 秒,分,时,日,月,周 5 | 6 | ## 管理界面 7 | ![](example/demo.jpeg) 8 | 9 | ## install 10 | - go.mod 11 | ```shell script 12 | require github.com/gohouse/crontab master 13 | ```` 14 | 15 | ## web管理简单用例 16 | ```go 17 | package main 18 | 19 | import ( 20 | "encoding/json" 21 | "fmt" 22 | "github.com/gohouse/crontab" 23 | "github.com/gohouse/crontab/client" 24 | "github.com/sirupsen/logrus" 25 | "log" 26 | "os" 27 | "time" 28 | ) 29 | 30 | type logFormater struct {} 31 | func (logFormater) Format(entry *logrus.Entry) ([]byte, error) { 32 | var marshal []byte 33 | if len(entry.Data) > 0 { 34 | marshal, _ = json.Marshal(entry.Data) 35 | } 36 | res := fmt.Sprintf("[%s] %s %s %s\n", entry.Level.String(), entry.Time.Format(time.RFC3339), entry.Message, marshal) 37 | return []byte(res),nil 38 | } 39 | func main() { 40 | var port = ":8200" 41 | // 日志 42 | logger := logrus.New() 43 | 44 | // 如果使用日志文件 45 | var logfile = "crontab.log" 46 | f, _ := os.OpenFile(logfile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0766) 47 | logger.SetOutput(f) 48 | logger.SetFormatter(logFormater{}) 49 | 50 | // 如果输出到控制台,则使用 os.Stdout 即可 51 | //logger.SetOutput(os.Stdout) 52 | 53 | // 初始化计划任务管理器 54 | // 这里使用了文件记录日志, 提供了logger接口, 可以自由扩充记录日志到数据库等其他地方 55 | tm := crontab.NewTaskManager(crontab.Logger(logger)) 56 | 57 | // 加入任务列表 58 | //TaskInit(tm) 59 | tm.AddGroup(TaskInit) 60 | 61 | // 开启 restful api 服务 62 | log.Fatal(client.Run(tm, port, logfile)) 63 | } 64 | 65 | func TaskInit(tm *crontab.TaskManager) { 66 | // test 每10s执行一次 67 | tm.Add("每10s执行一次", crontab.NewCronTab(crontab.CT_Second).SetSecond(10), Test) 68 | 69 | // 每天执行一次 statistic_of_per_day 70 | tm.Add("每天0时0分0秒执行的任务", crontab.NewCronTab(crontab.CT_Day).SetDay(1), Test) 71 | 72 | // 30分钟执行一次 73 | tm.Add("30分钟执行一次", 74 | crontab.NewCronTab(crontab.CT_Minute).SetMinute(30). 75 | RunOnceFirst(false), // 这一步操作是移除默认先执行一次,而是从30分钟后的 0s 开始周期执行第一次 76 | Test) 77 | } 78 | 79 | func Test(args ...interface{}) { 80 | // todo 这里就是你想干的事 81 | } 82 | 83 | ``` 84 | 访问 http://localhost:8200 即可方便的查看管理计划任务了 85 | 86 | ## 非web管理用例 87 | ### 1. 执行简单的任务 88 | ```go 89 | package main 90 | 91 | import ( 92 | "github.com/gohouse/crontab" 93 | "log" 94 | ) 95 | 96 | func main() { 97 | crontab.NewCronTab(crontab.CT_Second). 98 | SetSecond(3). 99 | Run(func(args ...interface{}) { 100 | log.Println("每 3s 会执行一次本操作") 101 | }) 102 | } 103 | ``` 104 | 输出 105 | ```go 106 | 2020/01/23 20:26:29 每 3s 会执行一次本操作 107 | 2020/01/23 20:26:32 每 3s 会执行一次本操作 108 | 2020/01/23 20:26:35 每 3s 会执行一次本操作 109 | ``` 110 | 111 | ### 2. 执行多个任务 112 | ```go 113 | package main 114 | 115 | import ( 116 | "fmt" 117 | "github.com/gohouse/crontab" 118 | "github.com/gohouse/golib/date" 119 | "log" 120 | "time" 121 | ) 122 | 123 | func main() { 124 | var job = crontab.NewTaskManager() 125 | 126 | cron := crontab.NewCronTab(crontab.CT_Second).SetSecond(3) 127 | cron2 := crontab.NewCronTab(crontab.CT_Second).SetSecond(3) 128 | job.Add("xxx", cron, teststr) 129 | job.Add("xxx222", cron2, teststrs) 130 | 131 | log.Println("start...") 132 | job.Start() 133 | //go func() { 134 | // time.Sleep(10*time.Second) 135 | // job.Stop() 136 | //}() 137 | job.Wait() 138 | } 139 | 140 | func teststr(args ...interface{}) { 141 | fmt.Println("xxx: ", time.Now().Format(date.DateTimeFormat)) 142 | } 143 | func teststrs(args ...interface{}) { 144 | fmt.Println("xxx222: ", time.Now().Format(date.DateTimeFormat)) 145 | } 146 | ``` 147 | 148 | ## restful api 149 | `GET /start` 启动所有任务 150 | `GET /start/{id}` 启动一个任务 151 | `GET /stop` 停止所有任务 152 | `GET /stop/{id}` 停止一个任务 153 | `GET /remove` 删除所有任务 154 | `GET /remove/{id}` 删除一个任务 155 | `GET /tasklist` 任务列表 156 | `GET /log?limit=20` 任务日志列表,limit为一次取最新多少条 157 | 158 | ## 各种用例参考 159 | 各个缺省值为: 秒(0),分(0),时(0),日(1),周(日),月(无) 160 | ```shell script 161 | # 每3s执行一次 162 | crontab.NewCronTab(crontab.CT_Second).SetSecond(3) 163 | # 每分钟的第5s执行一次 164 | crontab.NewCronTab(crontab.CT_Minute).SetMinute(1).SetSecond(5) 165 | # 每2小时的第0分5s执行一次,缺省分钟则默认为0,下同 166 | crontab.NewCronTab(crontab.CT_Hour).SetHour(2).SetSecond(5) 167 | # 每3天的0点0分5s执行一次 168 | crontab.NewCronTab(crontab.CT_Day).SetDay(3).SetSecond(5) 169 | # 每月1号的03点05分0s执行一次,缺省日期为1号,可通过 SetDay(3) 改变日期为3号等 170 | crontab.NewCronTab(crontab.CT_Month).SetMonth(1).SetHour(3).SetMinute(5) 171 | # 每周周日的0点5分0s执行一次 172 | crontab.NewCronTab(crontab.CT_Week).SetWeek(time.Sunday).SetMinute(5) 173 | ``` 174 | 所有计划任务再运行时,都会优先执行一次,如果不想先执行一次,则可以调用`RunOnceFirst(false)`即可,如 175 | ```shell script 176 | crontab.NewCronTab(crontab.CT_Second).SetSecond(3).RunOnceFirst(false) 177 | ``` 178 | > 周期任务本身不能为0,如: 按秒执行的周期不能为0s,即不能有0s的周期任务 -------------------------------------------------------------------------------- /client/client.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/gohouse/crontab" 6 | "github.com/gohouse/crontab/client/client_web" 7 | "github.com/gohouse/golib/file" 8 | "github.com/gohouse/golib/t" 9 | "log" 10 | "net/http" 11 | "sort" 12 | "strings" 13 | ) 14 | 15 | var tm *crontab.TaskManager 16 | var htmlRaw = client_web.LoadTemplate() 17 | var title = "golang计划任务" 18 | var logfile = "crontab.log" 19 | func Run(ctm *crontab.TaskManager, port string, logfile_ string,titles ...string) error { 20 | logfile = logfile_ 21 | if len(titles)>0{ 22 | title = titles[0] 23 | } 24 | tm = ctm 25 | // 启动web服务 26 | route := gin.Default() 27 | routeInit(route) 28 | log.Println("visit: http://localhost"+port) 29 | return route.Run(port) 30 | } 31 | 32 | func routeInit(route *gin.Engine) { 33 | //route.LoadHTMLGlob("client/client_web/*") 34 | route.GET("/", index) 35 | route.GET("/tasklist", taskList) 36 | route.GET("/new/:step", refresh) 37 | route.GET("/stop", stop) 38 | route.GET("/stop/:pkid", stop) 39 | route.GET("/start", start) 40 | route.GET("/start/:pkid", start) 41 | route.GET("/remove", remove) 42 | route.GET("/remove/:pkid", remove) 43 | route.GET("/log", logInfo) 44 | } 45 | 46 | func index(c *gin.Context) { 47 | //c.HTML(http.StatusOK, "index.html", nil) 48 | 49 | c.Header("Content-Type", "text/html; charset=utf-8") 50 | //var title = struct { 51 | // Title string 52 | //}{title} 53 | c.String(200, htmlRaw, title) 54 | } 55 | 56 | func start(c *gin.Context) { 57 | var pkid = c.Param("pkid") 58 | if pkid=="" { 59 | tm.Start() 60 | } else { 61 | tm.Start(pkid) 62 | } 63 | c.String(http.StatusOK, "启动:"+pkid) 64 | } 65 | func stop(c *gin.Context) { 66 | var pkid = c.Param("pkid") 67 | if pkid=="" { 68 | tm.Stop() 69 | } else { 70 | tm.Stop(pkid) 71 | } 72 | c.String(http.StatusOK, "停止:"+pkid) 73 | } 74 | func remove(c *gin.Context) { 75 | var pkid = c.Param("pkid") 76 | if pkid=="" { 77 | tm.Remove() 78 | } else { 79 | tm.Remove(pkid) 80 | } 81 | c.String(http.StatusOK, "删除:"+pkid) 82 | } 83 | func taskList(c *gin.Context) { 84 | var result = make(resultListStructSort, 0) 85 | _func := func(key, value interface{}) bool { 86 | val := value.(*crontab.TaskObject) 87 | var taskStatus = "已停止" 88 | if val.IsRunning() { 89 | taskStatus = "运行中" 90 | } 91 | result = append(result, map[string]interface{}{ 92 | "status": taskStatus, 93 | "id": key, 94 | "title": val.Title(), 95 | }) 96 | return true 97 | } 98 | tm.Range(_func) 99 | sort.Sort(sort.Reverse(result)) 100 | //c.Header("Content-Type", "text/html; charset=utf-8") 101 | c.JSON(http.StatusOK, result) 102 | } 103 | 104 | //重写map排序规则 105 | type resultListStructSort []map[string]interface{} 106 | 107 | func (p resultListStructSort) Len() int { return len(p) } 108 | func (p resultListStructSort) Less(i, j int) bool { 109 | return ToInt64(p[i]["id"]) > ToInt64(p[j]["id"]) 110 | } 111 | func (p resultListStructSort) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 112 | 113 | func refresh(c *gin.Context) { 114 | var step = c.Param("step") 115 | 116 | tm.Add("周期"+step+"s测试任务", 117 | crontab.NewCronTab(crontab.CT_Second).SetSecond(t.New(step).Int()).RunOnceFirst(), 118 | Test) 119 | } 120 | 121 | func logInfo(c *gin.Context) { 122 | var limit int64 = 20 123 | if r,ok:=c.GetQuery("limit");ok{ 124 | limit = t.New(r).Int64() 125 | } 126 | // 获取 127 | f := file.Tail_f(logfile, limit) 128 | c.JSON(http.StatusOK, strings.Split(strings.TrimSpace(f),"\n")) 129 | } 130 | 131 | func Test(args ...interface{}) { 132 | // todo 133 | } 134 | -------------------------------------------------------------------------------- /client/client_web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | 9 | 11 | 12 | golang crontab dashboard 13 | 14 | 15 | 16 |
17 |

golang计划任务

18 |
19 |
20 | 21 |

任务列表

22 |
23 | 3s周期的测试任务: 24 | 25 |
26 | 27 |
28 |   29 |   30 |   31 |
32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 54 | 55 |
id任务名字运行状态操作
56 | 57 | 58 | 59 |

60 | 61 | 由于不涉及数据传输,故都采用了 GET 请求

62 |
63 | 64 |

启动所有任务 api: /start

65 |

启动一个任务 api: /start/{id}

66 |

停止所有任务 api: /stop

67 |

停止一个任务 api: /stop/{id}

68 |

移除所有任务 api: /remove

69 |

移除一个任务 api: /remove/{id}

70 |

任务列表 api: /taskList

71 |

任务日志 api: /log?limit=20

72 |
73 |
74 |
75 | 76 | 77 |
78 | 79 |

运行日志

80 |
81 | 刷新日志(limit=20): 82 | 83 |
84 | 85 |
86 |
87 | 88 | 89 | 99 | 100 |
101 |
102 |
103 |
104 | 105 | 106 | 109 | 112 | 113 | 182 | 183 | -------------------------------------------------------------------------------- /client/client_web/load_as_raw.go: -------------------------------------------------------------------------------- 1 | package client_web 2 | 3 | // 下边的内容就是当前目录下 index.html 的内容, 只是为了方便使用 raw 调用, 写入到了代码中而已 4 | func LoadTemplate() string { 5 | return ` 6 | 7 | 8 | 9 | 11 | 12 | 13 | 15 | 16 | golang crontab dashboard 17 | 18 | 19 | 20 |
21 |

%s

22 |
23 |
24 | 25 |

任务列表

26 |
27 | 3s周期的测试任务: 28 | 29 |
30 | 31 |
32 |   33 |   34 |   35 |
36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 58 | 59 |
id任务名字运行状态操作
60 | 61 | 62 | 63 |

64 | 65 | 由于不涉及数据传输,故都采用了 GET 请求

66 |
67 | 68 |

启动所有任务 api: /start

69 |

启动一个任务 api: /start/{id}

70 |

停止所有任务 api: /stop

71 |

停止一个任务 api: /stop/{id}

72 |

移除所有任务 api: /remove

73 |

移除一个任务 api: /remove/{id}

74 |

任务列表 api: /taskList

75 |

任务日志 api: /log?limit=20

76 |
77 |
78 |
79 | 80 | 81 |
82 | 83 |

运行日志

84 |
85 | 刷新日志(limit=20): 86 | 87 |
88 | 89 |
90 |
91 | 92 | 93 | 103 | 104 |
105 |
106 |
107 |
108 | 109 | 110 | 113 | 116 | 117 | 186 | 187 | ` 188 | } -------------------------------------------------------------------------------- /cmd/crontable-web/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/gohouse/crontab" 7 | "github.com/gohouse/crontab/client" 8 | "github.com/sirupsen/logrus" 9 | "log" 10 | "os" 11 | "time" 12 | ) 13 | 14 | type logFormater struct {} 15 | func (logFormater) Format(entry *logrus.Entry) ([]byte, error) { 16 | var marshal []byte 17 | if len(entry.Data) > 0 { 18 | marshal, _ = json.Marshal(entry.Data) 19 | } 20 | res := fmt.Sprintf("[%s] %s %s %s\n", entry.Level.String(), entry.Time.Format(time.RFC3339), entry.Message, marshal) 21 | return []byte(res),nil 22 | } 23 | func main() { 24 | var port = ":8200" 25 | // 日志 26 | logger := logrus.New() 27 | 28 | // 如果使用日志文件 29 | var logfile = "crontab.log" 30 | f, _ := os.OpenFile(logfile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0766) 31 | logger.SetOutput(f) 32 | logger.SetFormatter(logFormater{}) 33 | 34 | // 如果输出到控制台,则使用 os.Stdout 即可 35 | //logger.SetOutput(os.Stdout) 36 | 37 | // 初始化计划任务管理器 38 | // 这里使用了文件记录日志, 提供了logger接口, 可以自由扩充记录日志到数据库等其他地方 39 | tm := crontab.NewTaskManager(crontab.Logger(logger)) 40 | 41 | // 加入任务列表 42 | //TaskInit(tm) 43 | tm.AddGroup(TaskInit) 44 | 45 | // 开启 restful api 服务 46 | log.Fatal(client.Run(tm, port, logfile)) 47 | } 48 | 49 | func TaskInit(tm *crontab.TaskManager) { 50 | // test 每10s执行一次 51 | tm.Add("每10s执行一次", crontab.NewCronTab(crontab.CT_Second).SetSecond(10), Test) 52 | 53 | // 每天执行一次 statistic_of_per_day 54 | tm.Add("每天0时0分0秒执行的任务", crontab.NewCronTab(crontab.CT_Day).SetDay(1), Test) 55 | 56 | // 30分钟执行一次 57 | tm.Add("30分钟执行一次", 58 | crontab.NewCronTab(crontab.CT_Minute).SetMinute(30). 59 | RunOnceFirst(false), // 这一步操作是移除默认先执行一次,而是从30分钟后的 0s 开始周期执行第一次 60 | Test) 61 | } 62 | 63 | func Test(args ...interface{}) { 64 | // todo 这里就是你想干的事 65 | } 66 | -------------------------------------------------------------------------------- /crontab.go: -------------------------------------------------------------------------------- 1 | package crontab 2 | 3 | import ( 4 | "context" 5 | "github.com/sirupsen/logrus" 6 | "sync/atomic" 7 | "time" 8 | ) 9 | 10 | type CronType int 11 | 12 | const ( 13 | CT_Month CronType = iota + 1 14 | CT_Week 15 | CT_Day 16 | CT_Hour 17 | CT_Minute 18 | CT_Second 19 | ) 20 | 21 | type CronValue struct { 22 | Month int 23 | Week time.Weekday 24 | Day int 25 | Hour int 26 | Minute int 27 | Second int 28 | } 29 | 30 | type HandleFunc func(args ...interface{}) 31 | 32 | type CronTab struct { 33 | ctx context.Context 34 | CronType 35 | cronv CronValue 36 | runOnceFirst bool 37 | running bool 38 | opt *Options 39 | runTimes int64 40 | } 41 | 42 | func NewCronTab(cron CronType, opts ...OptionHandleFunc) *CronTab { 43 | var opt = &Options{} 44 | for _, item := range opts { 45 | item(opt) 46 | } 47 | return &CronTab{ 48 | ctx: context.TODO(), 49 | CronType: cron, 50 | cronv: CronValue{ 51 | Month: 1, 52 | Day: 1, 53 | }, 54 | runOnceFirst: true, 55 | opt: opt, 56 | } 57 | } 58 | 59 | // RunOnceFirst 先运行一次 60 | func (ct *CronTab) RunOnceFirst(b ...bool) *CronTab { 61 | if len(b) > 0 { 62 | ct.runOnceFirst = b[0] 63 | } else { 64 | ct.runOnceFirst = true 65 | } 66 | 67 | return ct 68 | } 69 | 70 | func (ct *CronTab) SetMonth(arg int) *CronTab { 71 | if arg < 1 { 72 | panic("arg must > 0") 73 | } 74 | ct.cronv.Month = arg 75 | return ct 76 | } 77 | 78 | func (ct *CronTab) SetWeek(arg time.Weekday) *CronTab { 79 | ct.cronv.Week = arg 80 | return ct 81 | } 82 | 83 | func (ct *CronTab) SetDay(arg int) *CronTab { 84 | if arg < 0 { 85 | panic("arg must >= 0") 86 | } 87 | ct.cronv.Day = arg 88 | return ct 89 | } 90 | 91 | func (ct *CronTab) SetHour(arg int) *CronTab { 92 | if arg < 0 { 93 | panic("arg must >= 0") 94 | } 95 | ct.cronv.Hour = arg 96 | return ct 97 | } 98 | 99 | func (ct *CronTab) SetMinute(arg int) *CronTab { 100 | if arg < 0 { 101 | panic("arg must >= 0") 102 | } 103 | ct.cronv.Minute = arg 104 | return ct 105 | } 106 | 107 | func (ct *CronTab) SetSecond(arg int) *CronTab { 108 | if arg < 0 { 109 | panic("arg must >= 0") 110 | } 111 | ct.cronv.Second = arg 112 | return ct 113 | } 114 | 115 | func (ct *CronTab) IsRunning() bool { 116 | return ct.running 117 | } 118 | 119 | func (ct *CronTab) RunTimes() int64 { 120 | return ct.runTimes 121 | } 122 | 123 | func (ct *CronTab) Run(h HandleFunc, args ...interface{}) { 124 | if ct.opt.logger == nil { 125 | ct.opt.logger = logrus.New() 126 | } 127 | ct.running = true 128 | if ct.runOnceFirst { 129 | go h(args...) 130 | atomic.AddInt64(&ct.runTimes, 1) 131 | ct.opt.logger.Infof("第%v次执行任务:%v", ct.runTimes, args) 132 | } 133 | for { 134 | now := time.Now() 135 | next := ct._run(now) 136 | t := time.NewTimer(next.Sub(now)) 137 | defer t.Stop() 138 | select { 139 | case <-ct.ctx.Done(): 140 | ct.running = false 141 | //log.Println("done ...") 142 | return 143 | case <-t.C: 144 | //以下为定时执行的操作 145 | go h(args...) 146 | atomic.AddInt64(&ct.runTimes, 1) 147 | ct.opt.logger.Infof("第%v次执行任务:%v", ct.runTimes, args) 148 | } 149 | } 150 | } 151 | 152 | func (ct *CronTab) _run(now time.Time) time.Time { 153 | switch ct.CronType { 154 | case CT_Month: 155 | if ct.cronv.Month == 0 { 156 | panic("Month must > 0") 157 | } 158 | next := now.AddDate(0, ct.cronv.Month, 0) 159 | return time.Date(next.Year(), next.Month(), ct.cronv.Day, ct.cronv.Hour, ct.cronv.Minute, ct.cronv.Second, 0, next.Location()) 160 | case CT_Week: 161 | var days = time.Saturday - now.Weekday() + ct.cronv.Week + 1 162 | next := now.AddDate(0, int(days), 0) 163 | return time.Date(next.Year(), next.Month(), next.Day(), ct.cronv.Hour, ct.cronv.Minute, ct.cronv.Second, 0, next.Location()) 164 | case CT_Day: 165 | if ct.cronv.Day == 0 { 166 | panic("Day must > 0") 167 | } 168 | next := now.AddDate(0, 0, ct.cronv.Day) 169 | return time.Date(next.Year(), next.Month(), next.Day(), ct.cronv.Hour, ct.cronv.Minute, ct.cronv.Second, 0, next.Location()) 170 | case CT_Hour: 171 | if ct.cronv.Hour == 0 { 172 | panic("Hour must > 0") 173 | } 174 | next := now.Add(time.Hour * time.Duration(ct.cronv.Hour)) 175 | return time.Date(next.Year(), next.Month(), next.Day(), next.Hour(), ct.cronv.Minute, ct.cronv.Second, 0, next.Location()) 176 | case CT_Minute: 177 | if ct.cronv.Minute == 0 { 178 | panic("Minute must > 0") 179 | } 180 | next := now.Add(time.Minute * time.Duration(ct.cronv.Minute)) 181 | return time.Date(next.Year(), next.Month(), next.Day(), next.Hour(), next.Minute(), ct.cronv.Second, 0, next.Location()) 182 | case CT_Second: 183 | if ct.cronv.Second == 0 { 184 | panic("Second must > 0") 185 | } 186 | next := now.Add(time.Second * time.Duration(ct.cronv.Second)) 187 | return time.Date(next.Year(), next.Month(), next.Day(), next.Hour(), next.Minute(), next.Second(), 0, next.Location()) 188 | } 189 | return time.Now() 190 | } 191 | -------------------------------------------------------------------------------- /example/cron.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/gohouse/crontab" 5 | "log" 6 | "time" 7 | ) 8 | 9 | func main() { 10 | crontab.NewCronTab(crontab.CT_Second). 11 | SetSecond(3). 12 | SetWeek(time.Sunday). 13 | RunOnceFirst(). 14 | Run(func(args ...interface{}) { 15 | log.Println("每 3s 会执行一次本操作") 16 | }) 17 | } 18 | -------------------------------------------------------------------------------- /example/demo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gohouse/crontab/51c404d87b1ab946f80de4b4b09c81b471b73df8/example/demo.jpeg -------------------------------------------------------------------------------- /example/manager.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/gohouse/crontab" 6 | "github.com/gohouse/golib/date" 7 | "log" 8 | "time" 9 | ) 10 | 11 | func main() { 12 | var job = crontab.NewTaskManager() 13 | 14 | cron := crontab.NewCronTab(crontab.CT_Second).SetSecond(3) 15 | cron2 := crontab.NewCronTab(crontab.CT_Second).SetSecond(3) 16 | job.Add("xxx", cron, teststr) 17 | job.Add("xxx222", cron2, teststrs) 18 | 19 | log.Println("start...") 20 | job.Start() 21 | //go func() { 22 | // time.Sleep(10*time.Second) 23 | // job.Stop() 24 | //}() 25 | job.Wait() 26 | } 27 | 28 | func teststr(args ...interface{}) { 29 | fmt.Println("xxx: ", time.Now().Format(date.DateTimeFormat)) 30 | } 31 | func teststrs(args ...interface{}) { 32 | fmt.Println("xxx222: ", time.Now().Format(date.DateTimeFormat)) 33 | } 34 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/gohouse/crontab 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/gin-gonic/gin v1.5.0 7 | github.com/gohouse/golib v0.0.0-20200226112932-d6a5a50f91c6 8 | github.com/sirupsen/logrus v1.7.0 9 | ) 10 | -------------------------------------------------------------------------------- /task_manager.go: -------------------------------------------------------------------------------- 1 | package crontab 2 | 3 | import ( 4 | "context" 5 | "github.com/gohouse/golib/t" 6 | "github.com/sirupsen/logrus" 7 | "sync" 8 | "sync/atomic" 9 | ) 10 | 11 | var incId int64 12 | 13 | func GetId() int64 { return atomic.AddInt64(&incId, 1) } 14 | 15 | type TaskManager struct { 16 | store *sync.Map 17 | wg *sync.WaitGroup 18 | ctx context.Context 19 | opt *Options 20 | done chan struct{} 21 | } 22 | 23 | func NewTaskManager(opts ...OptionHandleFunc) *TaskManager { 24 | var opt = &Options{} 25 | for _, item := range opts { 26 | item(opt) 27 | } 28 | if opt.logger == nil { 29 | opt.logger = logrus.New() 30 | } 31 | return newTaskManager(opt) 32 | } 33 | 34 | func newTaskManager(opt *Options) *TaskManager { 35 | return &TaskManager{&sync.Map{}, &sync.WaitGroup{}, context.Background(), opt, make(chan struct{})} 36 | } 37 | 38 | func (job *TaskManager) Add(title string, cron *CronTab, callback HandleFunc, args ...interface{}) string { 39 | var taskId = t.New(GetId()).String() 40 | args = append(args, taskId, "-", title) 41 | cron.opt = job.opt 42 | var so = TaskObject{ 43 | cron: cron, 44 | callback: callback, 45 | args: args, 46 | title: title, 47 | taskId: taskId, 48 | } 49 | job.store.Store(taskId, &so) 50 | job.opt.logger.Infof("添加任务:%s - %s", taskId, title) 51 | return taskId 52 | } 53 | 54 | func (job *TaskManager) AddGroup(tl func(*TaskManager)) { 55 | tl(job) 56 | } 57 | 58 | func (job *TaskManager) Start(keys ...string) { 59 | if len(keys) > 0 { 60 | if r, ok := job.store.Load(keys[0]); ok { 61 | var so = r.(*TaskObject) 62 | job.wg.Add(1) 63 | go so.start() 64 | job.wg.Done() 65 | job.opt.logger.Infof("开始任务:%s - %s", so.taskId, so.title) 66 | } 67 | } else { 68 | job.store.Range(func(key, value interface{}) bool { 69 | job.wg.Add(1) 70 | var so = value.(*TaskObject) 71 | go so.start() 72 | job.wg.Done() 73 | job.opt.logger.Infof("开始任务:%s - %s", so.taskId, so.title) 74 | return true 75 | }) 76 | } 77 | } 78 | 79 | func (job *TaskManager) Wait() { 80 | job.wg.Wait() 81 | select {} 82 | } 83 | 84 | func (job *TaskManager) Stop(keys ...string) { 85 | if len(keys) > 0 { 86 | if r, ok := job.store.Load(keys[0]); ok { 87 | var so = r.(*TaskObject) 88 | if so.IsRunning() { 89 | so.stop() 90 | job.opt.logger.Infof("停止任务:%s - %s", so.taskId, so.title) 91 | } 92 | } 93 | } else { 94 | job.store.Range(func(key, value interface{}) bool { 95 | var so = value.(*TaskObject) 96 | so.stop() 97 | if so.IsRunning() { 98 | so.stop() 99 | job.opt.logger.Infof("停止任务:%s - %s", so.taskId, so.title) 100 | } 101 | return true 102 | }) 103 | } 104 | //// 判断是否还有任务 105 | //var jobs int 106 | //job.store.Range(func(key, value interface{}) bool { 107 | // jobs++ 108 | // return true 109 | //}) 110 | //if jobs == 0 { 111 | // job.done <- struct{}{} 112 | //} 113 | } 114 | 115 | func (job *TaskManager) Remove(keys ...string) { 116 | if len(keys) > 0 { 117 | job.Stop(keys[0]) 118 | job.store.Delete(keys[0]) 119 | job.opt.logger.Infof("删除任务:%s", keys[0]) 120 | } else { 121 | job.opt.logger.Infof("删除所有任务") 122 | job.Stop() 123 | *job = *newTaskManager(job.opt) 124 | } 125 | } 126 | 127 | func (job *TaskManager) Range(f func(key, value interface{}) bool) { 128 | job.store.Range(f) 129 | } 130 | -------------------------------------------------------------------------------- /tm_options.go: -------------------------------------------------------------------------------- 1 | package crontab 2 | 3 | import ( 4 | "github.com/sirupsen/logrus" 5 | ) 6 | 7 | type Options struct { 8 | logger *logrus.Logger 9 | } 10 | type OptionHandleFunc func(options *Options) 11 | 12 | func Logger(al *logrus.Logger) OptionHandleFunc { 13 | if al == nil { 14 | al = logrus.New() 15 | } 16 | return func(options *Options) { 17 | options.logger = al 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tm_task.go: -------------------------------------------------------------------------------- 1 | package crontab 2 | 3 | import "context" 4 | 5 | type TaskObject struct { 6 | cron *CronTab 7 | callback HandleFunc 8 | args []interface{} 9 | cancel context.CancelFunc 10 | title string 11 | taskId string 12 | } 13 | 14 | func (so *TaskObject) start() { 15 | if so.cron.running == true { 16 | return 17 | } 18 | ctx, cancel := context.WithCancel(context.Background()) 19 | so.cron.ctx = ctx 20 | so.cancel = cancel 21 | so.cron.Run(so.callback, so.args...) 22 | } 23 | func (so *TaskObject) stop() { 24 | if so.cron.running == false { 25 | return 26 | } 27 | (so.cancel)() 28 | } 29 | func (so *TaskObject) IsRunning() bool { 30 | return so.cron.IsRunning() 31 | } 32 | func (so *TaskObject) Title() string { 33 | return so.title 34 | } 35 | --------------------------------------------------------------------------------