There are many scheduled tasks in the business, in the specified time, whether or not the completion of the need for a callback, obviously, the need to implement a timer, the better is the time wheel and the minimum heap. Here we introduce the minimum heap implementation, which is a disguised topn problem.
This article is still in the continuous update changes, please go to the original address http://www.dmwan.cc/?p=146
Because it is to be used in the project, can not only consider the minimum heap to finish, need to add a few features, the first is to use a timer to implement the timing function, the second is to have the early deletion function. In particular, the 2nd, in the case of high concurrency, the timer can not let the task automatically expire, business success in the case, to be able to delete early, otherwise, the timer pressure will become larger;
Project GitHub Address: Https://github.com/caucy/timeloop.
Invocation Example:
package mainimport ("OS" "FMT" "Time" "Os/signal" "StrConv" "Syscall" "Timeloop/timer") var (timerctl *timer. Timerheaphandler) Func init () {timerctl = timer. New (}type) timerhandler struct {}func addtimertask (dueinterval int, taskId string) {Timerctl.addfuncwithid (time . Duration (Dueinterval) *time. Second, TaskId, func () {fmt. Printf ("TaskID is%v, time Duration is%v", TaskID, Dueinterval)})}func (t *timerhandler) Startloop () {Timerctl.starttime RLoop (timer. Min_timer)//scan interval time EQ CPU Hz/tick}func main () {sigs: = Make (chan os. Signal, 1) Signal. Notify (SIGs, Syscall. SIGINT, Syscall. SIGTERM) Timerentry: = Timerhandler{}timerentry.startloop () num: = 5000interval: = $ * time. Millisecondgo func () {for i: = 0; i < num; i++ {taskId: = StrConv. Itoa (i) Timerctl.addfuncwithid (*interval, TaskId, func () {fmt. Printf ("TaskID is%v, time Duration is%v \ n", TaskID, Interval)}) time. Sleep (* time. Millisecond)}} () <-sigs}
The main idea is to maintain a minimum heap, each time push,pop to adjust the heap to generate the smallest heap, a clock, every time to pop all timeout tasks, put into the asynchronous consumption queue. This kind of library is useful in high-frequency overtime task management.