### Install timingwheel Package Source: https://github.com/russellluo/timingwheel/blob/master/README.md Use this command to install the timingwheel package. Ensure you are using Go 1.16 or later. ```bash $ go get -u github.com/RussellLuo/timingwheel ``` -------------------------------- ### Manage Timers with TimingWheel Source: https://context7.com/russellluo/timingwheel/llms.txt A comprehensive example showing how to initialize a TimingWheel, schedule one-shot and recurring tasks, and handle timer cancellation. ```go package main import ( "fmt" "sync" "time" "github.com/RussellLuo/timingwheel" ) type IntervalScheduler struct { Interval time.Duration } func (s *IntervalScheduler) Next(prev time.Time) time.Time { return prev.Add(s.Interval) } func main() { // Create timing wheel with 1ms resolution tw := timingwheel.NewTimingWheel(time.Millisecond, 20) tw.Start() defer tw.Stop() var wg sync.WaitGroup // Example 1: One-shot timer wg.Add(1) tw.AfterFunc(100*time.Millisecond, func() { fmt.Println("One-shot timer fired at 100ms") wg.Done() }) // Example 2: Timer that gets cancelled cancelledTimer := tw.AfterFunc(500*time.Millisecond, func() { fmt.Println("This timer was cancelled and should not fire") }) // Example 3: Multiple timers at different intervals wg.Add(3) for i, delay := range []time.Duration{150, 200, 250} { d := delay * time.Millisecond idx := i + 1 tw.AfterFunc(d, func() { fmt.Printf("Timer %d fired at %v\n", idx, d) wg.Done() }) } // Example 4: Recurring timer with scheduler tickCount := 0 wg.Add(2) recurringTimer := tw.ScheduleFunc(&IntervalScheduler{75 * time.Millisecond}, func() { tickCount++ fmt.Printf("Recurring tick %d\n", tickCount) if tickCount <= 2 { wg.Done() } }) // Cancel the 500ms timer before it fires time.Sleep(50 * time.Millisecond) if cancelledTimer.Stop() { fmt.Println("Successfully cancelled the 500ms timer") } // Wait for all expected timers to complete wg.Wait() // Stop the recurring timer for !recurringTimer.Stop() { } fmt.Println("Recurring timer stopped") // Expected output (order may vary slightly): // Successfully cancelled the 500ms timer // Recurring tick 1 // One-shot timer fired at 100ms // Recurring tick 2 // Timer 1 fired at 150ms // Timer 2 fired at 200ms // Timer 3 fired at 250ms // Recurring timer stopped } ``` -------------------------------- ### Create and Start a New TimingWheel Source: https://context7.com/russellluo/timingwheel/llms.txt Initializes a new TimingWheel with a specified tick interval and wheel size. The wheel must be started before scheduling timers. ```go package main import ( "fmt" "time" "github.com/RussellLuo/timingwheel" ) func main() { // Create a timing wheel with 1ms tick and 20 buckets // This gives a time range of 20ms per wheel level tw := timingwheel.NewTimingWheel(time.Millisecond, 20) // Start the timing wheel (required before scheduling timers) tw.Start() defer tw.Stop() fmt.Println("TimingWheel started successfully") // Expected output: TimingWheel started successfully } ``` -------------------------------- ### Start Source: https://context7.com/russellluo/timingwheel/llms.txt Starts the timing wheel's internal goroutines that process expired timers. Must be called before scheduling any timers. The timing wheel uses a delay queue internally to efficiently wait for the next bucket expiration. ```APIDOC ## Start ### Description Starts the timing wheel's internal goroutines that process expired timers. Must be called before scheduling any timers. The timing wheel uses a delay queue internally to efficiently wait for the next bucket expiration. ### Method `Start` ### Endpoint N/A (Method on TimingWheel instance) ### Parameters None ### Request Example ```go package main import ( "time" "github.com/RussellLuo/timingwheel" ) func main() { tw := timingwheel.NewTimingWheel(time.Millisecond, 20) // Start the timing wheel - this spawns background goroutines tw.Start() // Always stop the timing wheel when done tw.Stop() } ``` ### Response #### Success Response (200) Starts the internal processing of the timing wheel. #### Response Example None (This is a method call, not an API endpoint returning data) ``` -------------------------------- ### Start TimingWheel Goroutines Source: https://context7.com/russellluo/timingwheel/llms.txt Starts the internal goroutines responsible for processing expired timers. This method must be called before any timers are scheduled. The timing wheel uses an internal delay queue for efficient waiting. ```go package main import ( "fmt" "time" "github.com/RussellLuo/timingwheel" ) func main() { tw := timingwheel.NewTimingWheel(time.Millisecond, 20) // Start the timing wheel - this spawns background goroutines tw.Start() fmt.Println("Timing wheel is running") // Always stop the timing wheel when done tw.Stop() fmt.Println("Timing wheel stopped") // Expected output: // Timing wheel is running // Timing wheel stopped } ``` -------------------------------- ### Schedule Recurring Tasks Source: https://context7.com/russellluo/timingwheel/llms.txt Schedules a function to execute repeatedly based on a `Scheduler`'s plan. The function runs in a goroutine and returns a `Timer` for cancellation. The example shows stopping a recurring timer. ```go package main import ( "fmt" "time" "github.com/RussellLuo/timingwheel" ) // EveryScheduler implements the Scheduler interface for fixed intervals type EveryScheduler struct { Interval time.Duration } func (s *EveryScheduler) Next(prev time.Time) time.Time { return prev.Add(s.Interval) } func main() { tw := timingwheel.NewTimingWheel(time.Millisecond, 20) tw.Start() defer tw.Stop() counter := 0 done := make(chan struct{}) // Schedule a recurring task every 300ms timer := tw.ScheduleFunc(&EveryScheduler{300 * time.Millisecond}, func() { counter++ fmt.Printf("Tick %d\n", counter) if counter >= 3 { done <- struct{}{} } }) // Wait for 3 ticks <-done // Stop the recurring timer - loop until fully stopped for !timer.Stop() { // Timer may be in the process of restarting, retry } fmt.Println("Recurring timer stopped") // Expected output: // Tick 1 // Tick 2 // Tick 3 // Recurring timer stopped } ``` -------------------------------- ### Run Benchmarks Source: https://github.com/russellluo/timingwheel/blob/master/README.md Execute the benchmark tests to evaluate the performance of the timingwheel implementation against standard Go timers. ```bash $ go test -bench=. -benchmem ``` -------------------------------- ### Implement Custom Schedulers Source: https://context7.com/russellluo/timingwheel/llms.txt Shows how to implement the Scheduler interface for custom execution plans. `EveryScheduler` fires at fixed intervals, and `LimitedScheduler` fires a fixed number of times, returning a zero time to stop. ```go package main import ( "fmt" "time" "github.com/RussellLuo/timingwheel" ) // EveryScheduler fires at fixed intervals type EveryScheduler struct { Interval time.Duration } func (s *EveryScheduler) Next(prev time.Time) time.Time { return prev.Add(s.Interval) } // LimitedScheduler fires a fixed number of times type LimitedScheduler struct { Interval time.Duration Max int count int } func (s *LimitedScheduler) Next(prev time.Time) time.Time { if s.count >= s.Max { return time.Time{} // Return zero time to stop } s.count++ return prev.Add(s.Interval) } func main() { tw := timingwheel.NewTimingWheel(time.Millisecond, 20) tw.Start() defer tw.Stop() // Create a scheduler that fires 3 times scheduler := &LimitedScheduler{ Interval: 200 * time.Millisecond, Max: 3, } done := make(chan struct{}) count := 0 tw.ScheduleFunc(scheduler, func() { count++ fmt.Printf("Scheduled task fired: iteration %d\n", count) if count >= 3 { close(done) } }) <-done // Expected output: // Scheduled task fired: iteration 1 // Scheduled task fired: iteration 2 // Scheduled task fired: iteration 3 } ``` -------------------------------- ### Implement DelayQueue in Go Source: https://context7.com/russellluo/timingwheel/llms.txt Demonstrates the usage of the unbounded blocking delayqueue subpackage to manage items with specific expiration times. ```go package main import ( "fmt" "time" "github.com/RussellLuo/timingwheel/delayqueue" ) func main() { // Create a delay queue with initial capacity of 10 dq := delayqueue.New(10) exitC := make(chan struct{}) // Start the polling goroutine go dq.Poll(exitC, func() int64 { return time.Now().UnixNano() / int64(time.Millisecond) }) // Get current time in milliseconds nowMs := time.Now().UnixNano() / int64(time.Millisecond) // Offer items with different expirations dq.Offer("first", nowMs+100) // expires in 100ms dq.Offer("second", nowMs+200) // expires in 200ms // Receive expired items from the channel fmt.Println("Waiting for items to expire...") item1 := <-dq.C fmt.Printf("Received: %v\n", item1) item2 := <-dq.C fmt.Printf("Received: %v\n", item2) close(exitC) // Expected output: // Waiting for items to expire... // Received: first // Received: second } ``` -------------------------------- ### NewTimingWheel Source: https://context7.com/russellluo/timingwheel/llms.txt Creates a new TimingWheel instance with a specified tick interval and wheel size. The tick determines the minimum time resolution, while wheel size controls the number of buckets in each timing wheel level. ```APIDOC ## NewTimingWheel ### Description Creates a new TimingWheel instance with a specified tick interval and wheel size. The tick determines the minimum time resolution, while wheel size controls the number of buckets in each timing wheel level. ### Method `NewTimingWheel` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "time" "github.com/RussellLuo/timingwheel" ) func main() { // Create a timing wheel with 1ms tick and 20 buckets tw := timingwheel.NewTimingWheel(time.Millisecond, 20) // Start the timing wheel (required before scheduling timers) ttw.Start() defer tw.Stop() } ``` ### Response #### Success Response (200) Returns a pointer to a new TimingWheel instance. #### Response Example ```json { "timingWheel": "" } ``` ``` -------------------------------- ### Stop a Scheduled Timer Source: https://context7.com/russellluo/timingwheel/llms.txt Demonstrates how to stop a timer before it fires. Returns true if stopped successfully, false otherwise. For recurring timers, multiple calls might be needed. ```go package main import ( "fmt" "time" "github.com/RussellLuo/timingwheel" ) func main() { tw := timingwheel.NewTimingWheel(time.Millisecond, 20) tw.Start() defer tw.Stop() // Schedule a timer for 1 second in the future timer := tw.AfterFunc(time.Second, func() { fmt.Println("This should not print") }) // Wait 500ms then cancel the timer time.Sleep(500 * time.Millisecond) stopped := timer.Stop() if stopped { fmt.Println("Timer was stopped before firing") } else { fmt.Println("Timer had already fired or was stopped") } // Wait a bit to verify timer doesn't fire time.Sleep(600 * time.Millisecond) fmt.Println("Done - timer did not fire") // Expected output: // Timer was stopped before firing // Done - timer did not fire } ``` -------------------------------- ### ScheduleFunc Source: https://context7.com/russellluo/timingwheel/llms.txt Schedules a function to execute according to a Scheduler's execution plan. The function runs in its own goroutine each time. ```APIDOC ## ScheduleFunc ### Description Schedules a function to execute according to a Scheduler's execution plan. The function runs in its own goroutine each time. Returns a Timer that can be used to cancel future executions. ``` -------------------------------- ### Schedule Function Execution with AfterFunc Source: https://context7.com/russellluo/timingwheel/llms.txt Schedules a function to execute after a specified duration, similar to time.AfterFunc. The function runs in its own goroutine upon timer expiration. Returns a Timer object that can be used to cancel the scheduled task. ```go package main import ( "fmt" "time" "github.com/RussellLuo/timingwheel" ) func main() { tw := timingwheel.NewTimingWheel(time.Millisecond, 20) tw.Start() defer tw.Stop() done := make(chan struct{}) start := time.Now() // Schedule a function to run after 1 second tw.AfterFunc(time.Second, func() { elapsed := time.Since(start) fmt.Printf("Timer fired after %v\n", elapsed.Round(time.Millisecond)) close(done) }) // Wait for the timer to fire <-done // Expected output: // Timer fired after 1s } ``` -------------------------------- ### Scheduler Interface Source: https://context7.com/russellluo/timingwheel/llms.txt The Scheduler interface defines the execution plan for recurring tasks. Implement the Next(time.Time) time.Time method to control when the next execution occurs. ```APIDOC ## Scheduler Interface ### Description The Scheduler interface defines the execution plan for recurring tasks. Implement the `Next(time.Time) time.Time` method to control when the next execution occurs. Return a zero time to stop scheduling. ``` -------------------------------- ### AfterFunc Source: https://context7.com/russellluo/timingwheel/llms.txt Schedules a function to execute after a specified duration. Similar to `time.AfterFunc`, the function runs in its own goroutine when the timer expires. Returns a Timer that can be used to cancel the scheduled task. ```APIDOC ## AfterFunc ### Description Schedules a function to execute after a specified duration. Similar to `time.AfterFunc`, the function runs in its own goroutine when the timer expires. Returns a Timer that can be used to cancel the scheduled task. ### Method `AfterFunc` ### Endpoint N/A (Method on TimingWheel instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "time" "github.com/RussellLuo/timingwheel" ) func main() { tw := timingwheel.NewTimingWheel(time.Millisecond, 20) tw.Start() defer tw.Stop() done := make(chan struct{}) start := time.Now() // Schedule a function to run after 1 second tw.AfterFunc(time.Second, func() { elapsed := time.Since(start) fmt.Printf("Timer fired after %v\n", elapsed.Round(time.Millisecond)) close(done) }) // Wait for the timer to fire <-done } ``` ### Response #### Success Response (200) Returns a `Timer` object which can be used to cancel the scheduled function. #### Response Example ```json { "timer": "" } ``` ``` -------------------------------- ### Stop Source: https://context7.com/russellluo/timingwheel/llms.txt Stops the timing wheel and waits for all internal goroutines to finish. Does not wait for any running timer tasks to complete - the caller must coordinate with running tasks explicitly if needed. ```APIDOC ## Stop ### Description Stops the timing wheel and waits for all internal goroutines to finish. Does not wait for any running timer tasks to complete - the caller must coordinate with running tasks explicitly if needed. ### Method `Stop` ### Endpoint N/A (Method on TimingWheel instance) ### Parameters None ### Request Example ```go package main import ( "fmt" "time" "github.com/RussellLuo/timingwheel" ) func main() { tw := timingwheel.NewTimingWheel(time.Millisecond, 20) tw.Start() // Schedule some work tw.AfterFunc(100*time.Millisecond, func() { fmt.Println("Timer fired") }) // Give the timer time to fire time.Sleep(200 * time.Millisecond) // Stop the timing wheel - blocks until internal goroutines exit tw.Stop() fmt.Println("Timing wheel stopped cleanly") } ``` ### Response #### Success Response (200) Stops the internal processing of the timing wheel and waits for goroutines to exit. #### Response Example None (This is a method call, not an API endpoint returning data) ``` -------------------------------- ### Stop TimingWheel Source: https://context7.com/russellluo/timingwheel/llms.txt Stops the timing wheel and waits for its internal goroutines to exit. This method does not wait for any running timer tasks to complete; the caller must coordinate with them explicitly if necessary. ```go package main import ( "fmt" "time" "github.com/RussellLuo/timingwheel" ) func main() { tw := timingwheel.NewTimingWheel(time.Millisecond, 20) tw.Start() // Schedule some work tw.AfterFunc(100*time.Millisecond, func() { fmt.Println("Timer fired") }) // Give the timer time to fire time.Sleep(200 * time.Millisecond) // Stop the timing wheel - blocks until internal goroutines exit tw.Stop() fmt.Println("Timing wheel stopped cleanly") // Expected output: // Timer fired // Timing wheel stopped cleanly } ``` -------------------------------- ### Timer.Stop Source: https://context7.com/russellluo/timingwheel/llms.txt Prevents a scheduled timer from firing. Returns true if the timer was successfully stopped, false if it had already expired or been stopped. ```APIDOC ## Timer.Stop ### Description Prevents a scheduled timer from firing. Returns true if the timer was successfully stopped, false if it had already expired or been stopped. For recurring timers, may need to be called in a loop to ensure the timer is fully stopped. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.