-
Notifications
You must be signed in to change notification settings - Fork 0
/
Timer.ahk
103 lines (94 loc) · 2.63 KB
/
Timer.ahk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
Extended library for Timer
(c) 2022-2024 Ken Verdadero
2022-11-19
*/
/**
* Timer class.
* A class-based approach to using timers in AutoHotkey.
*
* @class Timer
*
* @property {Integer} period - The period of the timer
* @property {Integer} priority - The priority of the timer
* @property {Integer} defPeriod - The default period of the timer
* @property {Integer} defPriority - The default priority of the timer
*
* @example
*
* timer := Timer(MyAppObj, "AutoSave", 1000 * 60, 0)
* timer.Start()
*/
class Timer {
__New(obj, method := "Call", defPeriod := 250, defPriority := 0, proxyCallback := "") {
this.period := defPeriod
this.priority := defPriority
this.__callback := Format("{1}.{2}", Type(obj), method)
this.proxyCallbackFunc := proxyCallback
this.callback := ObjBindMethod(this, "_ProxyCallback", ObjBindMethod(obj, method)) ;; ! Params in ObjBindMethod is not supported
this.running := false
}
/**
* A middleware for the callback
* @param obj the actual callback function
*/
_ProxyCallback(obj) {
if Type(this.proxyCallbackFunc) == "Func" {
this.proxyCallbackFunc.Call()
}
obj.Call()
}
/**
* Sets the period of the timer
* @param {Integer} value
*/
SetPeriod(value := 250) {
if Type(value) != "Integer" {
throw TypeError("Expected an Integer type. Got " Type(value), , value)
}
this.period := value
}
/**
* Sets the priority of the timer
* @param {Integer} value
*/
SetPriority(value := 0) {
if Type(value) != "Integer" {
throw TypeError("Expected an Integer type. Got " Type(value), , value)
}
this.priority := value
}
/**
* Starts the timer
* @param {String} period interval in milliseconds
* @param {String} priority level of priority
*/
Start(period := '', priority := '') {
if this.IsRunning() {
return
}
period := (StrLen(period) ? period : this.period)
SetTimer(
this.callback,
period,
(StrLen(priority) ? priority : this.priority),
)
this.running := (period < 0 ? 0 : 1)
}
/**
* Stops the timer
*/
Stop() {
try {
SetTimer(this.callback, 0)
this.running := false
}
catch Error as e {
throw Error(Format("Cannot terminate timer: {1}", e.Message), , e.Extra)
}
}
/**
* Returns the running status of the timer
*/
IsRunning() => (this.running ? 1 : 0)
}