I have some code that needs to be executed at specific user-defined times of day (e.g. at 11:45:30 am). My code looks like this:
void OnTimer(UINT nTimerID)
{
if(nTimerID == somethingTimerId_)
{
presenter_.DoSomething();
}
else if(nTimerID == updateClockTimerId_)
{
// this timer goes off once per second.
UpdateTimeDisplay();
presenter_.ExecuteTaskIfExecuteTime();
presenter_.ExecuteOtherTaskIfExecuteTime();
}
}
ExecuteTaskIfExecuteTime()
checks the curent time and checks a list for times to execute it's task; if the current time is one of those times, it then executes the task.
ExecuteOtherTaskIfExecuteTime()
does the same thing but has it's own list of times to execute and it's own task.
Now I need to add a third task type and I'm feeling like it's time to generalize this and make it more flexible.
So I'm wondering if a command pattern would be appropriate here. What I'm thinking is making a command for each type of task, I'll add a command object with a time to execute to a list of commands and iterate over that list in once per second. For each command object it will compare the command time against the current time and if they are equal (or within a small threshold) execute the command object. So my code would become:
else if(nTimerID == updateClockTimerId_)
{
// this timer goes off once per second.
UpdateTimeDisplay();
presenter_.ProcessCommands();
}
Is this a correct use of the command pattern? I'm open to different ideas as well.