[Bug]: Correct usage of Ticker and Timer #22222
Labels
kind/bug
Issues or changes related a bug
kind/improvement
Changes related to something improve, likes ut and code refactor
stale
indicates no udpates for 30 days
triage/accepted
Indicates an issue or PR is ready to be actively worked on.
Milestone
Is there an existing issue for this?
Environment
Current Behavior
Timer Vesus Ticker
Timers — These are used for one-off tasks. It represents a single event in the future.
You tell the timer how long you want to wait, and it provides a channel that will be notified at that time. You can call Stop prevents the Timer from firing.
Stop returns true if the call stops the timer, false if the timer has already expired or been stopped.
Tickers — Tickers are exceptionally helpful when you need to perform an action repeatedly at given time intervals.
We can use tickers, in combination with goroutines to run these tasks in the background of our applications.
For repeated- tasks, use Ticker
Although Timer can also help to achieve this (Reset, for example), there are many details that need to be paid attention to, especially in the case of Stop (You can refer to this discussion golang/go#27169 ).
When using Ticker, remember to stop it to release associated resources.
For one-off task, use Timer or time.After
As for time.After, it waits for the duration to elapse and then sends the current time on the returned channel. It is equivalent to NewTimer(d).C.
The underlying Timer is not recovered by the garbage collector until the timer fires. If efficiency is a concern, use NewTimer instead and call Timer.Stop if the timer is no longer needed.
Avoid using time.After when you have a For loop
In this use case, it may cause a large number of Timer objects to be created, although these large objects will be GCed later.
Do not use time.Tick
Tick is a convenience wrapper for NewTicker providing access to the ticking channel only.
While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks".
In milvus, there is no such usage scenario, so the use of time.Tick is prohibited
Expected Behavior
No response
Steps To Reproduce
No response
Milvus Log
No response
Anything else?
No response
The text was updated successfully, but these errors were encountered: