Difference between revisions of "Lua:Class:Timer"

From Cheat Engine
Jump to navigation Jump to search
(added details and various examples)
(Major overhaul of the post.)
Line 1: Line 1:
 
[[Category:Lua]]
 
[[Category:Lua]]
== Timer ==
+
{{CodeBox|'''class''' Timer ''':''' Component}}
  
Timer is a non-visual component class that fires an event at regular intervals. Timers are created with the [[Lua:createTimer|createTimer]] function and inherit from the [[Lua:Class:Component|Component]] class.
+
The Timer class represents a timer component.
  
Timers execute callbacks periodically (persistent mode) or once with auto-cleanup (one-shot mode).
+
A Timer inherits from Component and Object. It can repeatedly call an OnTimer function after a given interval, or it can be created as a one-shot timer that executes a callback once and then destroys itself.
  
 +
===Inheritance===
 +
{|width="85%" cellpadding="10%" cellspacing="0" border="0"
 +
!align="left"|Class
 +
!align="left"|Inherits From
 +
!style="width: 80%;background-color:white;" align="left"|Description
 +
|-
 +
|Timer
 +
|Component
 +
|A timer component that can execute code after a delay or repeatedly at an interval.
 +
|-
 +
|Component
 +
|Object
 +
|Base class for components.
 +
|}
  
== Class Hierarchy ==
+
===Creation===
 +
{{CodeBox|'''function''' createTimer(''delay'', ''function'', ''...'') ''':''' Timer}}
 +
{{CodeBox|'''function''' createTimer(''owner'', ''enabled'') ''':''' Timer}}
  
* [[Lua:Class:Object|Object]]
+
Creates a Timer object.
** [[Lua:Class:Component|Component]]
 
*** '''Timer'''
 
  
 +
The first form creates a one-shot timer that waits for the given delay, executes the given function, and then destroys itself. Do not use the timer object after it has fired.
  
== Creation ==
+
The second form creates a persistent timer object. If ''enabled'' is omitted, it will be enabled by default and starts running as soon as an OnTimer event has been assigned. The owner may be nil, but in that case you are responsible for destroying the timer manually.
  
Timers are created using [[Lua:createTimer|createTimer]]:
+
===Function Parameters===
 
+
====One-Shot Timer====
local timer = createTimer()              -- Persistent timer
+
{|width="85%" cellpadding="10%" cellspacing="0" border="0"
createTimer(1000, function() end)        -- One-shot timer
+
!align="left"|Parameter
 +
!align="left"|Type
 +
!style="width: 80%;background-color:white;" align="left"|Description
 +
|-
 +
|delay
 +
|Integer
 +
|The delay in milliseconds before the callback is executed.
 +
|-
 +
|function
 +
|Function
 +
|The function to execute when the timer fires.
 +
|-
 +
|...
 +
|Any (optional)
 +
|Additional arguments that are passed to the callback function.
 +
|}
  
 +
====Persistent Timer====
 +
{|width="85%" cellpadding="10%" cellspacing="0" border="0"
 +
!align="left"|Parameter
 +
!align="left"|Type
 +
!style="width: 80%;background-color:white;" align="left"|Description
 +
|-
 +
|owner
 +
|Component or nil (optional)
 +
|The owner of the timer. If nil or omitted, the timer must be destroyed manually.
 +
|-
 +
|enabled
 +
|Boolean (optional)
 +
|If true, the timer is enabled. If omitted, the timer is enabled by default.
 +
|}
  
== Properties ==
+
===Returns===
 +
Timer — The created Timer object.
  
{|width="85%" cellpadding="10%" cellpadding="5%" cellspacing="0" border="0"
+
===Properties===
 +
{|width="85%" cellpadding="10%" cellspacing="0" border="0"
 
!align="left"|Property
 
!align="left"|Property
 
!align="left"|Type
 
!align="left"|Type
!align="left"|Access
+
!style="width: 80%;background-color:white;" align="left"|Description
!style="width: 65%;" align="left"|Description
 
 
|-
 
|-
 
|Interval
 
|Interval
|integer
+
|Integer
|Read/Write
+
|The number of milliseconds between timer executions. 1000 equals one second.
|Timer interval in '''milliseconds''' (1000 = 1 second). Must be greater than 0. Changes take effect on next timer tick.
 
 
|-
 
|-
 
|Enabled
 
|Enabled
|boolean
+
|Boolean
|Read/Write
+
|If true, the timer is active. If false, the timer is paused.
|Whether the timer is currently active. '''true''' = timer fires events, '''false''' = paused. Setting to '''false''' pauses without destroying. Setting to '''true''' resumes or starts the timer.
 
 
|-
 
|-
 
|OnTimer
 
|OnTimer
|function
+
|Function
|Read/Write
+
|The function to call when the timer triggers. The timer object is passed as the parameter.
|Callback function executed each time the timer fires. Function receives the timer object as first parameter (sender). For one-shot timers, set during creation; for persistent timers, set this property.
 
 
|}
 
|}
  
 +
===Methods===
 +
{|width="85%" cellpadding="10%" cellspacing="0" border="0"
 +
!align="left"|Method
 +
!align="left"|Return Type
 +
!style="width: 80%;background-color:white;" align="left"|Description
 +
|-
 +
|getInterval()
 +
|Integer
 +
|Returns the timer interval in milliseconds.
 +
|-
 +
|setInterval(interval)
 +
|void
 +
|Sets how often the timer should trigger, in milliseconds.
 +
|-
 +
|getOnTimer()
 +
|Function
 +
|Returns the current OnTimer function.
 +
|-
 +
|setOnTimer(function(timer))
 +
|void
 +
|Sets the function that is called when the timer triggers.
 +
|-
 +
|getEnabled()
 +
|Boolean
 +
|Returns whether the timer is currently enabled.
 +
|-
 +
|setEnabled(boolean)
 +
|void
 +
|Enables or disables the timer.
 +
|}
  
== Methods ==
+
===Examples===
 
+
<pre>
Inherits all methods from [[Lua:Class:Component|Component]]:
+
local timer = createTimer(nil, false)
 
 
'''destroy()'''
 
* Stops and destroys the timer
 
* Frees allocated memory
 
* '''Important:''' Do not call on one-shot timers (they auto-destroy)
 
 
 
 
 
=== Getter/Setter Methods ===
 
 
 
While properties can be accessed directly, you can also use explicit getter/setter methods:
 
 
 
'''getInterval() / setInterval(interval)'''
 
local timer = createTimer()
 
timer.setInterval(1000)
 
print(timer.getInterval())  -- Output: 1000
 
 
 
'''getEnabled() / setEnabled(enabled)'''
 
local timer = createTimer()
 
timer.setEnabled(false)
 
print(timer.getEnabled())  -- Output: false
 
 
 
'''getOnTimer() / setOnTimer(function)'''
 
local timer = createTimer()
 
timer.setOnTimer(function() print("Fired") end)
 
 
 
''Note:'' Direct property access is preferred in Lua (e.g., '''timer.Interval''' instead of '''timer.setInterval()''')
 
 
 
  
== Usage Examples ==
+
timer.Interval = 1000
 +
timer.OnTimer = function(timer)
 +
  print("Tick")
 +
end
  
=== Basic Examples ===
+
timer.Enabled = true
 +
</pre>
  
''Note:'' Examples in this section focus on timer functionality. For production code, ensure proper cleanup by using an owner (see [[#Ownership and Cleanup|Ownership and Cleanup]]) or manually calling '''destroy()''' when done.
+
<pre>
 +
local timer = createTimer()
 +
timer.Interval = 1000
  
'''Basic periodic callback:'''
+
local count = 0
-- Note: No cleanup - timer persists until CE closes
 
local timer = createTimer()
 
timer.Interval = 1000  -- 1 second
 
timer.OnTimer = function(sender)
 
  print("Current time: " .. os.date("%H:%M:%S"))
 
end
 
  
'''Self-stopping timer:'''
+
timer.OnTimer = function(timer)
local timer = createTimer()
+
  count = count + 1
timer.Interval = 1000
+
  print("Count: " .. tostring(count))
local count = 0
 
 
timer.OnTimer = function(sender)
 
  count = count + 1
 
  print("Count: " .. count)
 
 
 
  if count >= 5 then
 
    sender.Enabled = false
 
    print("Timer stopped")
 
  end
 
end
 
  
'''Pause and resume timer:'''
+
  if count >= 5 then
-- Note: No cleanup - timer persists until CE closes
+
    timer.Enabled = false
local timer = createTimer()
+
    timer.destroy()
timer.Interval = 500
+
  end
timer.OnTimer = function()
+
end
  print("Active")
+
</pre>
end
 
 
-- Pause
 
timer.Enabled = false
 
print("Paused")
 
 
-- Resume after delay
 
sleep(2000)
 
timer.Enabled = true
 
print("Resumed")
 
  
 +
<pre>
 +
createTimer(2000, function()
 +
  print("This runs once after 2 seconds")
 +
end)
 +
</pre>
  
=== Ownership and Cleanup ===
+
<pre>
 +
createTimer(1500, function(name, value)
 +
  print(name .. ": " .. tostring(value))
 +
end, "Health", 100)
 +
</pre>
  
'''Timer with manual cleanup:'''
+
<pre>
local timer = createTimer()
+
local form = createForm()
timer.Interval = 100
+
form.Caption = "Timer Example"
local iterations = 0
 
 
timer.OnTimer = function(sender)
 
  iterations = iterations + 1
 
 
 
  if iterations >= 100 then
 
    sender.destroy()
 
    timer = nil
 
    print("Timer destroyed after 100 iterations")
 
  end
 
end
 
  
'''Timer owned by form (auto-cleanup):'''
+
local timer = createTimer(form)
local form = createForm()
+
timer.Interval = 500
local timer = createTimer(form)
+
timer.OnTimer = function(timer)
+
  form.Caption = os.date("%H:%M:%S")
timer.Interval = 500
+
end
timer.OnTimer = function()
 
  form.Caption = "Time: " .. os.date("%H:%M:%S")
 
end
 
 
-- Timer is destroyed automatically when form closes
 
 
 
'''Timer owned by main form (auto-cleanup on CE close):'''
 
local timer = createTimer(getMainForm())
 
timer.Interval = 1000
 
timer.OnTimer = function()
 
  -- Runs until Cheat Engine closes
 
  print("Active: " .. os.date("%H:%M:%S"))
 
end
 
 
 
 
 
=== Advanced Examples ===
 
 
 
'''Dynamic interval adjustment:'''
 
-- Note: No cleanup - timer persists until CE closes
 
local timer = createTimer()
 
local speed = 1000
 
 
function setSpeed(newSpeed)
 
  speed = newSpeed
 
  timer.Interval = speed
 
end
 
 
timer.Interval = speed
 
timer.OnTimer = function()
 
  print("Tick at " .. speed .. "ms interval")
 
end
 
 
-- Change speed
 
setSpeed(500)
 
 
 
'''Memory monitoring:'''
 
-- Uses getMainForm() for automatic cleanup
 
local timer = createTimer(getMainForm())
 
timer.Interval = 100
 
 
timer.OnTimer = function()
 
  local playerHealthAddr = getAddress("player.health")
 
  if playerHealthAddr then
 
    local health = readInteger(playerHealthAddr)
 
   
 
    if health < 20 then
 
      print("WARNING: Low health!")
 
      -- Could trigger auto-heal here
 
    end
 
  else
 
    timer.Enabled = false
 
    print("Address not found, stopping monitor")
 
  end
 
end
 
 
 
'''Periodic auto-save:'''
 
-- Uses getMainForm() for automatic cleanup
 
local saveTimer = createTimer(getMainForm())
 
saveTimer.Interval = 60000  -- 1 minute
 
 
saveTimer.OnTimer = function()
 
  saveTable("autosave.ct")
 
  print("Table auto-saved at " .. os.date())
 
end
 
 
 
'''Multiple coordinated timers:'''
 
-- Note: No cleanup - timers persist until CE closes
 
local fastTimer = createTimer()
 
local slowTimer = createTimer()
 
 
fastTimer.Interval = 100
 
fastTimer.OnTimer = function()
 
  print("Fast: " .. os.clock())
 
end
 
 
slowTimer.Interval = 1000
 
slowTimer.OnTimer = function()
 
  print("Slow: " .. os.clock())
 
end
 
 
 
'''Throttled function execution:'''
 
-- Note: No cleanup - timer persists until CE closes
 
local timer = createTimer(nil, false)
 
timer.Interval = 1000
 
 
local actionQueue = {}
 
 
timer.OnTimer = function()
 
  if #actionQueue > 0 then
 
    local action = table.remove(actionQueue, 1)
 
    action()
 
  end
 
 
 
  if #actionQueue == 0 then
 
    timer.Enabled = false
 
  end
 
end
 
 
function queueAction(fn)
 
  table.insert(actionQueue, fn)
 
  timer.Enabled = true
 
end
 
 
-- Usage
 
queueAction(function() print("Action 1") end)
 
queueAction(function() print("Action 2") end)
 
 
 
'''Timer state machine:'''
 
-- Properly destroys itself when done
 
local timer = createTimer()
 
local state = "init"
 
 
timer.Interval = 1000
 
timer.OnTimer = function()
 
  if state == "init" then
 
    print("Initializing...")
 
    state = "loading"
 
    timer.Interval = 2000
 
   
 
  elseif state == "loading" then
 
    print("Loading...")
 
    state = "ready"
 
    timer.Interval = 100
 
   
 
  elseif state == "ready" then
 
    print("Ready!")
 
    timer.Enabled = false
 
    timer.destroy()
 
  end
 
end
 
 
 
 
 
== Callback Details ==
 
 
 
The '''OnTimer''' callback receives the timer object as its first parameter:
 
 
 
timer.OnTimer = function(sender)
 
  -- sender is the timer object
 
  print("Interval: " .. sender.Interval)
 
  print("Enabled: " .. tostring(sender.Enabled))
 
 
 
  -- Can modify the timer from within callback
 
  sender.Interval = 500
 
  sender.Enabled = false
 
end
 
 
 
For one-shot timers, additional parameters can be passed:
 
 
 
createTimer(1000, function(arg1, arg2)
 
  print(arg1)  -- "Hello"
 
  print(arg2)  -- "World"
 
end, "Hello", "World")
 
 
 
 
 
== Common Patterns ==
 
 
 
'''Initialization pattern:'''
 
local function createUpdateTimer(form, interval)
 
  local timer = createTimer(form)
 
  timer.Interval = interval
 
  return timer
 
end
 
 
local form = createForm()
 
local updateTimer = createUpdateTimer(form, 1000)
 
updateTimer.OnTimer = function()
 
  -- Update form
 
end
 
 
 
'''Delayed execution pattern:'''
 
function executeAfter(milliseconds, callback)
 
  createTimer(milliseconds, callback)
 
end
 
 
executeAfter(2000, function()
 
  print("Executed after 2 seconds")
 
end)
 
 
 
'''Periodic check pattern:'''
 
function watchAddress(address, checkInterval, callback)
 
  local timer = createTimer()
 
  timer.Interval = checkInterval
 
  timer.OnTimer = function()
 
    local value = readInteger(address)
 
    callback(value)
 
  end
 
  return timer
 
end
 
 
local watcher = watchAddress("game.exe+12345", 500, function(value)
 
  print("Current value: " .. value)
 
end)
 
 
 
 
 
== Technical Notes ==
 
 
 
=== Timer Resolution and Accuracy ===
 
 
 
* Timers have a system-dependent resolution (typically '''~15ms''' on Windows)
 
* Very short intervals (<15ms) may not fire exactly on schedule
 
* Timers are not real-time and can be affected by system load
 
* For high-precision timing, consider using [[Lua:createThread|createThread]] with sleep
 
* Timer callbacks execute in the main CE thread, blocking the UI if they run too long
 
 
 
 
 
=== Memory Management ===
 
 
 
'''Persistent timers:'''
 
* Destruction happens automatically if owned by a component that gets destroyed
 
* Use '''getMainForm()''' as owner to auto-cleanup when CE closes: '''createTimer(getMainForm())'''
 
* Otherwise must be explicitly destroyed with '''destroy()'''
 
* Forgetting to destroy causes memory leaks
 
 
 
'''One-shot timers:'''
 
* Automatically destroy themselves after firing
 
* '''Never''' call '''destroy()''' on one-shot timers
 
* Created with '''createTimer(interval, callback)''' syntax
 
 
 
 
 
=== Thread Safety ===
 
 
 
* Timer callbacks execute in the '''main CE thread'''
 
* Safe to update UI elements from timer callbacks
 
* No synchronization needed for CE API calls
 
* Long-running callbacks will freeze the CE interface
 
  
 +
form.show()
 +
</pre>
  
 
{{LuaSeeAlso}}
 
{{LuaSeeAlso}}
 
=== Related Functions ===
 
* [[Lua:createTimer|createTimer]] - Create timer objects
 
* [[Lua:sleep|sleep]] - Blocking delay
 
* [[Lua:createThread|createThread]] - Background threading
 
 
=== Related Classes ===
 
* [[Lua:Class:Component|Component]] - Base class documentation
 

Revision as of 19:21, 23 June 2026

<> Reference

class Timer : Component

The Timer class represents a timer component.

A Timer inherits from Component and Object. It can repeatedly call an OnTimer function after a given interval, or it can be created as a one-shot timer that executes a callback once and then destroys itself.

Inheritance

Class Inherits From Description
Timer Component A timer component that can execute code after a delay or repeatedly at an interval.
Component Object Base class for components.

Creation

<> Reference

function createTimer(delay, function, ...) : Timer

<> Reference

function createTimer(owner, enabled) : Timer

Creates a Timer object.

The first form creates a one-shot timer that waits for the given delay, executes the given function, and then destroys itself. Do not use the timer object after it has fired.

The second form creates a persistent timer object. If enabled is omitted, it will be enabled by default and starts running as soon as an OnTimer event has been assigned. The owner may be nil, but in that case you are responsible for destroying the timer manually.

Function Parameters

One-Shot Timer

Parameter Type Description
delay Integer The delay in milliseconds before the callback is executed.
function Function The function to execute when the timer fires.
... Any (optional) Additional arguments that are passed to the callback function.

Persistent Timer

Parameter Type Description
owner Component or nil (optional) The owner of the timer. If nil or omitted, the timer must be destroyed manually.
enabled Boolean (optional) If true, the timer is enabled. If omitted, the timer is enabled by default.

Returns

Timer — The created Timer object.

Properties

Property Type Description
Interval Integer The number of milliseconds between timer executions. 1000 equals one second.
Enabled Boolean If true, the timer is active. If false, the timer is paused.
OnTimer Function The function to call when the timer triggers. The timer object is passed as the parameter.

Methods

Method Return Type Description
getInterval() Integer Returns the timer interval in milliseconds.
setInterval(interval) void Sets how often the timer should trigger, in milliseconds.
getOnTimer() Function Returns the current OnTimer function.
setOnTimer(function(timer)) void Sets the function that is called when the timer triggers.
getEnabled() Boolean Returns whether the timer is currently enabled.
setEnabled(boolean) void Enables or disables the timer.

Examples

local timer = createTimer(nil, false)

timer.Interval = 1000
timer.OnTimer = function(timer)
  print("Tick")
end

timer.Enabled = true
local timer = createTimer()
timer.Interval = 1000

local count = 0

timer.OnTimer = function(timer)
  count = count + 1
  print("Count: " .. tostring(count))

  if count >= 5 then
    timer.Enabled = false
    timer.destroy()
  end
end
createTimer(2000, function()
  print("This runs once after 2 seconds")
end)
createTimer(1500, function(name, value)
  print(name .. ": " .. tostring(value))
end, "Health", 100)
local form = createForm()
form.Caption = "Timer Example"

local timer = createTimer(form)
timer.Interval = 500
timer.OnTimer = function(timer)
  form.Caption = os.date("%H:%M:%S")
end

form.show()

See Also

Main Pages