Тема: AHK: Class Timer
Добрейшего всем, давно хотел такой таймер, который вызывается определенное кол-во раз без лишних телодвижений в коде. Решил для этого написать класс и поделиться, дабы получить возможные доработки.
class Timer
{
__new(handler, timeout, count := "infinity", callOnInit := false)
{
this.Events.stop := this.stop
this.handler := (IsObject(handler) ? handler : func(handler))
this.timeout := timeout
this.count := count
if (this.timeout < 0)
{
this.count := 1
}
funcObj := ObjBindMethod(this.Events, "onTimer")
this.funcObj := funcObj
if (callOnInit)
{
this.Events.onTimer()
}
this.start()
}
__delete()
{
funcObj := this.funcObj
setTimer, % funcObj, delete
}
stop()
{
funcObj := this.funcObj
if (funcObj)
{
setTimer, % funcObj, off
}
}
start()
{
funcObj := this.funcObj
if (funcObj && (this.count == "infinity" || this.count > 0))
{
setTimer, % funcObj, % this.timeout
}
}
class Events
{
onTimer()
{
if (this.count != "infinity")
{
this.count -= 1
}
this.handler.call(this.count)
if (this.count == 0)
{
this.stop()
}
}
}
count[]
{
get
{
return this.Events.count
}
set
{
this.Events.count := value
return this.Events.count
}
}
handler[]
{
get
{
return this.Events.handler
}
set
{
this.Events.handler := value
return this.Events.handler
}
}
}
Основная цель - чтобы функция вызывалась указанное количество раз через определенное время.
Допустим данный код вызовет функцию 5 раз каждую 1с:
timerHandler := new Timer("test", 1000, 5)
test()
{
toolTip, % A_TickCount
}
А так мы можем узнать, сколько еще раз вызовет функцию:
timerHandler := new Timer("test", 1000, 5)
test(count)
{
toolTip, % A_TickCount " | Осталось: " count
}
Так мы можем сразу вызвать функцию при объявлении таймера:
timerHandler := new Timer("test", 1000, 5, true)
test(count)
{
toolTip, % A_TickCount " | Осталось: " count
}
Так же можно вызывать функцию с указанными параметрами:
timerHandler := new Timer(func("test").bind("параметр 1", "параметр 2"), 1000, 5, true)
test(param1, param2)
{
toolTip, % A_TickCount " | Param1: " Param1 " | Param2: " Param2
}
Если не указывать количество, то таймер будет работать как и обычный - бесконечно:
timerHandler := new Timer(func("test").bind("параметр 1", "параметр 2"), 1000)
test(param1, param2)
{
toolTip, % A_TickCount " | Param1: " Param1 " | Param2: " Param2
}
Если не указывать количество, то таймер будет работать как и обычный и вызываться при объявлении:
timerHandler := new Timer(func("test").bind("параметр 1", "параметр 2"), 1000,, true)
test(param1, param2)
{
toolTip, % A_TickCount " | Param1: " Param1 " | Param2: " Param2
}