cDelay Delay Object - TODO and Roadmap
vb
'===========================================================================
' Name: cDelay
' Description: Delay object class - supports event-triggered, callback,
' and synchronous wait modes
' Author: Deng Wei, QQ: 215879458
' Website: https://vb6.pro
' Date: 2026-03-31
' Reference: cTimer.cls architecture
'===========================================================================Current Version: v1.0
Implemented Features
- [x] Three working modes: Event, Callback, Sync
- [x] ParamArray variable parameter support (up to 9)
- [x] Sync mode message pump implementation (without DoEvents)
- [x] Sync mode cancellation
- [x] Automatic lifecycle management (reference counting)
- [x] Chainable API design
Roadmap
v1.1 Enhanced Multi-Instance Management
Based on Toast implementation, implement more powerful multi-instance management:
1.1.1 Instance Naming and Tracking
vb
' Set name for delay instance for easier management
Dim delay As New cDelay
delay.Tag("AutoSaveTimer").Callback(Me, "AutoSave").CountDown(5000)
' Get instance status by name
If Delays.Exists("AutoSaveTimer") Then
Debug.Print "Remaining time: " & Delays("AutoSaveTimer").RemainingTime
End IfImplementation Points:
- Add
Tagproperty/method supporting chainable calls - Global collection uses Key (such as "id:" & TimerID or custom Tag)
- Provide
Delays.Exists(Tag)method to check if instance exists - Provide
Delays(Tag)indexer to get instance reference
1.1.2 Group Management by Type
Based on Toast's 9 position collections, group by usage:
vb
' Enum definition
Public Enum DelayGroup
dgSystem = 1 ' System-level delay
dgUser = 2 ' User operation related
dgBackground = 3 ' Background tasks
dgAnimation = 4 ' Animation related
End Enum
' Usage
delay.Group(dgBackground).Callback(Me, "SyncData").CountDown(60000)
' Batch operations
delay.Group(dgBackground).CancelAll ' Cancel all background tasksImplementation Points:
- Each Group corresponds to an independent Collection
- Support group-level batch operations (CancelAll, PauseAll, ResumeAll)
1.1.3 Instance Status Query
vb
' Get count of currently active delays
Dim count As Long
count = Delays.Count ' Total
count = Delays.CountByGroup(dgSystem) ' By group
' Enumerate all active instances
Dim d As cDelay
For Each d In Delays
Debug.Print d.Tag & " - Remaining: " & d.RemainingTime
NextNew Properties/Methods:
RemainingTime- Remaining milliseconds (calculated property)ElapsedTime- Elapsed millisecondsProgress- Completion percentage (0-100)
v1.2 New Delay Methods (Same level as CountDown)
1.2.1 ClockAt - Specify Absolute Time
vb
' Execute at 14:30 today
delay.ClockAt "14:30:00".Callback(Me, "DoSomething")
' Specify date and time
delay.ClockAtDate "2026-04-01 09:00:00".Callback(Me, "MeetingReminder")
' Tomorrow at 8 AM
delay.ClockAtDate DateAdd("d", 1, Date) & " 08:00:00"Implementation Points:
- Calculate difference between target time and current time
- If target time has passed, choose to execute immediately or next day
- Support repetition: daily/weekly/monthly at the same time
1.2.2 Interval - Repeating Interval
vb
' Execute once every 5 seconds
delay.Interval(5000).Callback(Me, "CheckStatus")
' Limited count
delay.Interval(1000).RepeatCount(10).Callback(Me, "UpdateProgress")
' Stop
delay.StopIntervalImplementation Points:
- Internal use of Windows timer or loop
- Support infinite repetition or specified count
- Can dynamically modify interval time
1.2.3 Random - Random Delay
vb
' Random between 1-5 seconds
delay.Random(1000, 5000).Callback(Me, "RandomTask")
' Use for anti-detection, simulate human operations1.2.4 WaitUntil - Conditional Wait
vb
' Wait for a condition to be true (up to 10 seconds)
delay.WaitUntil(AddressOf IsDataReady, 10000).Callback(Me, "ProcessData")
' With function
Public Function IsDataReady() As Boolean
IsDataReady = (FileLen("data.txt") > 0)
End FunctionImplementation Points:
- Poll and check condition in message loop
- Support timeout
- Can set check interval (default 100ms)
1.2.5 Debounce
vb
' Execute search after 500ms of no input
delay.Debounce(500).Callback(Me, "DoSearch")
' Use cases: search box, window resize
' When triggered frequently, only the last one executes1.2.6 Throttle
vb
' Execute at most once every 2 seconds
delay.Throttle(2000).Callback(Me, "SaveLog")
' Use cases: logging, scroll events
' When triggered frequently, execute at fixed rate1.2.7 AfterLast - Execute After Idle
vb
' Execute after 3 seconds of no mouse/keyboard input
delay.AfterLastInput(3000).Callback(Me, "AutoSave")
' With specific events
delay.AfterLast("MouseMove", 1000).Callback(Me, "ShowTooltip")Implementation Points:
- Need to listen to system messages or poll GetLastInputInfo
- Reset timer when new input arrives
1.2.8 Retry - Retry Mechanism
vb
' Auto retry on failure, max 3 times, increasing interval
delay.Retry(3, 1000, 2).Callback(Me, "ConnectServer")
' After 1st failure wait 1s, 2nd wait 2s, 3rd wait 4s
' With callback return value to determine success
Public Function ConnectServer() As Boolean
' Return False will automatically trigger retry
ConnectServer = AttemptConnection()
End Function1.2.9 Schedule - Multi-Time Scheduling
vb
' Multiple time points in a day
delay.Schedule(Array("09:00", "12:00", "18:00")).Callback(Me, "CheckMail")
' Weekday scheduling
delay.ScheduleWeekday("09:00,12:00,18:00").Callback(Me, "CheckMail")1.2.10 DelayAfter - Delay After Event
vb
' Auto backup 5 seconds after file modification
delay.AfterEvent("FileChanged", "C:\data.txt", 5000).Callback(Me, "BackupFile")
' Auto save after window loses focus
delay.AfterEvent("LostFocus", Me.hWnd, 1000).Callback(Me, "AutoSave")v1.3 Advanced Control Features
1.3.1 Pause and Resume
vb
delay.CountDown(10000) ' 10 second delay
' Pause
delay.Pause ' Pause timing
Debug.Print delay.RemainingTime ' How much time remains
' Resume
delay.Resume ' Continue from where it pausedTechnical Approach:
- When pausing, record
PausedTickandRemainingAtPause - When resuming, recalculate
EndTick = GetTickCount() + RemainingAtPause - Only applicable to Windows timer mode (event/callback)
1.3.2 Reset and Modify
vb
' Reset current delay (start from beginning)
delay.Reset
' Modify remaining time
delay.ChangeDelay 5000 ' Change to 5 seconds remaining
' Add time
delay.AddTime 2000 ' Add 2 secondsv1.4 Performance and Debugging Enhancements
1.4.1 Debug Mode
vb
' Enable global debug
Delays.DebugMode = True
' Output logs
' [cDelay] AutoSaveTimer: CountDown started, 5000ms
' [cDelay] AutoSaveTimer: Tick, remaining 3000ms
' [cDelay] AutoSaveTimer: OnTime fired
' [cDelay] AutoSaveTimer: Cancelled by user1.4.2 Performance Statistics
vb
' Get statistics
Dim stats As DelayStats
stats = Delays.GetStats
Debug.Print "Total created: " & stats.TotalCreated
Debug.Print "Total completed: " & stats.TotalCompleted
Debug.Print "Total cancelled: " & stats.TotalCancelled
Debug.Print "Average execution time: " & stats.AvgExecutionTime1.4.3 Memory Monitoring
vb
' Auto cleanup zombie instances (optional)
Delays.AutoCleanup = True
Delays.AutoCleanupInterval = 60000 ' Check every 60 secondsv1.5 Sync Mode Enhancements
1.5.1 Timeout Handling
vb
' Sync mode supports timeout callback
delay.Sync().Timeout(5000).OnTimeout(Me, "OnSyncTimeout").CountDown(10000)
' If not completed within 10 seconds, trigger OnSyncTimeout after 5 seconds1.5.2 Conditional Wait
vb
' Wait until condition is met or timeout
delay.Sync().WaitUntil(AddressOf CheckCondition, 5000)
' Check CheckCondition function every frame, return True to end early1.5.3 Multi-Task Wait
vb
' Wait for all multiple delays to complete
Dim tasks As New Collection
tasks.Add delay1
tasks.Add delay2
tasks.Add delay3
Delay.WaitAll(tasks, 10000) ' Wait max 10 seconds
' Or wait for any to complete
Delay.WaitAny(tasks, 10000)v1.6 Callback Enhancements
1.6.1 Lambda/Anonymous Function Support (VB6 Simulation)
vb
' Use AddressOf to pass function pointer
delay.Callback(AddressOf MyStaticFunc).CountDown(1000)
' Or use class instance method
delay.Callback2(Me, "MethodName", param1, param2)1.6.2 Async Callback
vb
' Callback executes in independent thread (use with caution)
delay.AsyncCallback(Me, "HeavyTask").CountDown(100)1.6.3 Callback Chain
vb
' Multiple callbacks execute in order
delay.Callback(Me, "Step1") _
.Then(Me, "Step2") _
.Then(Me, "Step3") _
.CountDown(1000)
' After 1000ms, execute Step1 -> Step2 -> Step3 in sequencev1.7 Integration and Extensions
1.7.1 Integration with UI Controls
vb
' Auto update progress bar
delay.BindProgressBar(ProgressBar1).CountDown(5000)
' Auto update label
delay.BindLabel(Label1, "Time remaining: {remaining}s").CountDown(5000)1.7.2 Sound Support
vb
delay.OnTimeSound("C:\Windows\Media\chimes.wav").CountDown(5000)
delay.OnCancelSound("C:\Windows\Media\ding.wav")1.7.3 Configuration File Support
vb
' Load from configuration
delay.LoadConfig("AutoSaveDelay")
' Read from registry/INI: Delay.AutoSaveDelay = 5000v2.0 Architecture Refactoring (Long-term)
2.0.1 COM Component
- Compile as ActiveX DLL
- Support cross-project reuse
- Provide strongly-typed interfaces
2.0.2 Multi-threading Support
- True background thread timer
- Does not depend on Windows message queue
- Suitable for windowless environments (like Windows Service)
2.0.3 .NET Interoperability
- Provide .NET wrapper class
- Support calling from VB.NET/C#
Priority Recommendations
High Priority (Near-term Implementation)
- Instance naming and tracking - Basic functionality, many advanced features depend on it
- ClockAt - Execute at specified time, very practical feature
- Interval - Repeating interval execution, similar to timer
- Debounce/Throttle - Essential for UI development
- Debug mode - Easier development and troubleshooting
Medium Priority (Mid-term Implementation)
- Group management by type
- Pause/Resume functionality
- Random delay
- WaitUntil conditional wait
- Performance statistics
Low Priority (Long-term Consideration)
- Retry mechanism
- Multi-time scheduling
- Multi-task wait
- Callback chain
- COM component
Design Principles
- Backward Compatibility: All new features are optional, do not affect existing API
- Chainable Calls: Maintain
object.Method().Another().Action()style - Reasonable Defaults: Provide smart default behavior when not set
- Error Handling: All operations have clear error status and return values
- Resource Safety: Ensure no memory leaks, thorough cleanup
Contribution Suggestions
If you want to participate in development, here are some entry points:
- Documentation: Supplement more usage examples and best practices
- Test Cases: Write boundary condition tests (like extreme time values, concurrent scenarios)
- Performance Optimization: Optimize message loop, reduce CPU usage
- Code Review: Check thread safety and resource release
Reference Resources
- Toast multi-instance management:
D:\code\vi\vbmanlib\vbman\src\Toast\cToast.cls - Windows Timer API: MSDN
SetTimer/KillTimer - VB6 message loop:
PeekMessage/DispatchMessage - Design patterns: Observer pattern, Factory pattern, Object pool
Last Updated: 2026-03-31