Stop leaks Ticker when executing a function on the server

Hello, I have such a question, in general there is a server that processes some function, this function has a ticker set, when this function ends, the ticker.Stop () stops, that’s the problem, if I run this function not from the server, that’s all normally the ticker stops as the function is executed, but when launched from the server the ticker leaks indefinitely

the ticker itself

func cmdTicker() {
ticker := time.NewTicker(time.Second)
now := time.Now()

for range ticker.C {
	fmt.Println(fmt.Sprintf("%s", time.Since(now)))
	//timeProc = append(timeProc, fmt.Sprintf("%s", time.Since(now)))
}

ticker.Stop()
}

ticker launch

func Scan(cmd *pb.ScanCommandReq) []*models.Cmdprun {

wgAllScan := new(sync.WaitGroup)
//while the function is running ticker goes
go cmdTicker()

go func(wg *sync.WaitGroup) {
	for res := range resultsCh {
		if res.stateProc == 0 {
			host, err := resultfiles.ParseXMLResultFile(res.fileScan)
			if err != nil {
				log.Printf("Parsing file not done: %s", err)
			}

			results = append(results, host)

			err = os.Remove(res.fileScan)
			if err != nil {
				log.Fatal("Can't delete file", res.fileScan, err)
			}
		}
		wg.Done()
	}

}(wgAllScan)

wgAllScan.Wait()
close(resultsCh)

return results
}

Can someone come in handy when faced with a similar task. Solved this issue by checking to get the value into the channel, and stopping the ticker

func cmdTicker() {
   ticker := time.NewTicker(time.Second)
   now := time.Now()

for {
	// Select statement
	select {
	// Case statement
	case <-chTicker:
		ticker.Stop()
		fmt.Println("Scanning Completed!")
		return

	// Case to print ticker
	case <-ticker.C:
		fmt.Println(fmt.Sprintf("%s", time.Since(now)))
	}
}
}

And in the function itself, we send a successful completion

chTicker <- true
1 Like

I was thinking the same thing when I saw your question from my phone but I hadn’t made the time to get back to you sooner! Glad you figured it out and posted the solution :+1:

1 Like