Skip to content

Instantly share code, notes, and snippets.

@RonnyAL
Last active January 22, 2022 15:01
Show Gist options
  • Save RonnyAL/7b7838c6ec6273d97619f2cc567061dc to your computer and use it in GitHub Desktop.
Save RonnyAL/7b7838c6ec6273d97619f2cc567061dc to your computer and use it in GitHub Desktop.
A demonstration of time-based functions in AutoHotkey.
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
#SingleInstance Force
; #Warn ; Enable warnings to assist with detecting common errors.
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
profiles := []
InsertionSort(array)
{
For i, v in array
list .= v . "`n"
Sort, list, N A
Return StrSplit(RTrim(list, "`n"), "`n")
}
WaitAndRun(profile, sleepTimeS) {
MsgBox % "Will run " . profile.name . " in " . sleepTimeS . " seconds."
Sleep, % sleepTimeS * 1000
profile.Call()
}
CheckNext() {
global profiles
normalizedTimes := []
for index, p in profiles {
target := p.normalizedTime
if (target < A_Now) {
EnvAdd, target, 1, d
}
normalizedTimes.Push(target)
}
normalizedTimes := InsertionSort(normalizedTimes)
target := normalizedTimes[1]
for index, p in profiles {
if (p.normalizedTime == target) {
EnvSub, target, %A_Now%, Seconds
WaitAndRun(p, target)
}
}
}
class Profile {
__New(name, function, time) {
global profiles
this.name := name
this.function := Func(function)
this.time := time
this.normalizedTime := A_YYYY . A_MM . A_DD . time . "00"
profiles.Push(this)
}
__Call() {
this.function()
Sleep, 60000 ; Wait 1 min so that the function wont run twice
CheckNext()
}
}
morning() {
MsgBox, Good morning!
; Do morning stuff.
}
midday() {
MsgBox, Good day!
; Do day stuff.
}
evening() {
MsgBox, Good evening!
; Do evening stuff.
}
new Profile("Midday", "midday", "1200")
new Profile("Evening", "evening", "1600")
new Profile("Morning", "morning", "0800")
CheckNext()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment