Go perform timed tasks

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Write your own go timer to perform the task, welcome to shoot bricks.

Package Mainimport ("FMT" "Time" "Bufio" "OS" "Strings" "Errors" "Io/ioutil" "StrConv" "RegExp" "Net/http") var taskList []*tasktype mytimer struct{Config []map[string]interface{}}func newmytimer () *mytimer{return &mytim Er{}}func (t *mytimer) Start () {for _, V: = range t.config{//For each setting, start task MyTask: = NewTask (v) mytask.sta RT () TaskList = append (TaskList, MyTask)} fmt. Println ("----------Timer Started---------")}func (t *mytimer) Stop () {For _, Task: = Range tasklist{task. Stop ()}//Empty Task list taskList = make ([]*task, 0) fmt. Println ("---------Timer stoped----------")}func (t *mytimer) Restart () {t.stop () T.start () fmt. Println ("--------Timer restarted----------")}func (t *mytimer) loadconfigfile (fileName string) error{File,err:=os. Open (fileName) if nil!=err{return errors. New ("Config file load failed:" +filename)} defer file. Close () Config:=make ([]map[string]interface{}, 0) content,ok:=ioutil. REadall (file) if ok!=nil{return errors. New ("read config file error")} str:=string (content) reg:=regexp. Mustcompile ("[\r\n]+") Array: = Reg. Split (str,-1) for _,val:=range array{//#, which starts with a comment if strings. Hasprefix (Val, "#") | | Strings. Hasprefix (Val, ";") {Continue} If Len (val) > 0{kv: = Strings.         Split (val, "|") M:=make (map[string]interface{}) m["url"] = kv[0] If Len (kv) > 1{m["duration"], _ = StrConv.  Atoi (kv[1])} else {m["duration"] = ten} If Len (kv) > 2{m["Times"], _ = StrConv. Atoi (kv[2])} else {m["times"] = 1} config = append (config, m)}} t.config   = config; return Nil}type Task struct{times int Duration int URL string Ch chan int}func newtask (v map[string]interface{}) *task{C:=make (Chan int,1) return &task{times:v["Times"]. ( int), duration:v["Duration"]. (int), url:v["URL "]. (string), Ch:c}}func (Task *task) Start () {timer: = time. Newticker (time. Duration (Task. Duration) * time. Second) go func (c chan int) {if task. Times = = 0{Forend1:for {select{case <-timer. C:http. Get (Task. URL) fmt. PRINTLN ("Task request URL:" +task.  URL) Case <-c:break ForEnd1}}} else {Forend2:for I: = 0; I < Task. times; I ++{select{case <-timer. C:http. Get (Task. URL) fmt. PRINTLN ("Task request URL:" +task. URL) Case <-c:break ForEnd2}}//After execution completes, the timer for k,v needs to be destroyed:               = Range tasklist{If v = = task{if k = = 0{TaskList = tasklist[1:] } else if (k + 1) = = Len (taskList) {taskList = Tasklist[:k]} else {task List = AppEnd (tasklist[k+1:], tasklist[:k+2] ...) } Break}}} (task. CH)}func (Task *task) Stop () {task. Ch <-1 FMT. PRINTLN ("---task stoped---")}func main () {//console input Reader:=bufio. Newreader (OS. Stdin) Timer:=newmytimer () Ok:=timer. Loadconfigfile ("Config.txt") if ok!=nil{fmt. Println (OK)//Panic ("Error")} for{FMT. Println ("Enter a Command:") Rawline,_,_:=reader. ReadLine () command:=string (rawline) if "q" = = Command | | "Quit" = = command{timer. Stop () fmt. Println ("Bye") break} else If "start" = = command{timer. Start ()} else if "stop" = = command{timer. Stop ()} else if "restart" = = Command {timer. Restart ()} else if "help" = = command {fmt. Println ("****welcome to use mytimer****") fmt. Println ("There is commands and options:") fmt. Println ("Start--start task Jobs") fmt. Println ("Stop--stop TASK jobs ") fmt. PRINTLN ("Restart--restart jobs") fmt. Println ("Quit--quit the job task, also can use short command Q") fmt. Println ("Help--help infomation of MyTimer")} else {fmt. Println ("Unknow Command")}}}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.