I have designed an applet, that performs several routine tasks:
- once a day, on a specific times stored in the Preference file (plist)
- every hour, at the exact minute defined in the Preference file (plist).
The format for the point (1) is (as an example): “14:45” (every day, at this time, routing will be launched)
The format for the point (2) is (as an example): “:15” (which means at 00:15, 01:15 etc…)
The information from the preference file is transferrend into the corresponding properties during the applet initialisation (which is called in the on run/end run handler), which I will skip it here for simplicity.
property dailyRoutineTasks : “14:45”
property hourlyRoutineTasks : “:15”
The important part of the code is in idle handler, also for simplicity I am positing only the code that is relevant for monitoring the daily schedule (since it is very similar to the hourly schedule).
Basically, what I have so far is that every idle cycle (= every one second):
a) formatting the current time;
b) comparing the current (formatted) time with that of the stored into dailyRoutineTasks variable;
c) when are equal → call the subroutine (for launching all daily tasks).
But then I realised that for the full minute (in our example is until the time change into 14:46), I will be calling the subroutine (aprox) 60 times!!!
To avoid this I am using a boolean (suspendDailyRoutineTask = true/false).
Is there any better way to achieve this?
Thanks !
This is the code I have so far :
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
use framework "Foundation"
property dailyRoutineTasks : "14:45"
property hourlyRoutineTasks : ":15"
property suspendHourlyRoutineTask : false
property suspendDailyRoutineTask : false
on idle
set df to current application's NSDateFormatter's new()
df's setDateFormat:"HH:mm"
set theDateString to (df's stringFromDate:(current date)) as text
if not suspendDailyRoutineTask then -- initially this is 'false'. After become true (when the times are the same), this is ignored (thus avoiding calling the subroutines 60 times.
if theDateString = dailyRoutineTasks then -- 14:45
set suspendDailyRoutineTask to true
runRoutineTasks()
end if
else -- resetting the suspend boolean, which will occurs after the minute change (=60 seconds)
if ((text 4 thru -1 of theDateString) as integer) > ((text 4 thru -1 of dailyRoutineTasks) as integer) then -- here we are comparing only the minutes of the correpsonding tie stamp. And when 1 minutes is passed the 1st part of the comparison will be bigger than the second, and thus setting the boolean back to false, allowing again the analysis of the block of code above
set suspendDailyRoutineTask to false
end if
end if
return 1
end idle
on runRoutineTasks()
-- task_1
-- task_2
end runRoutineTasks