I am setting up a system to allow users to create custom queries that run at various intervals. So I could have 7 that run every 4 minutes, 10 that run every 6 minutes, and 3 that run every 10 minutes. (It could be many more though). What is the best way to set this up without just creating a bunch of timer objects?

2 Answers

4
Chris Dunaway On Best Solutions

One way would be to have a timer that ticks every minute and a variable that keeps track of the minutes. Then use an if statement to execute the tasks when the minute is a multiple of the desired time. This way you can have one timer serving multiple intervals.

For example:

private int timerCount = 0;

private void Timer_Tick(object sender, EventArgs e)
{
    //Increase this counter each time the timer ticks.
    timerCount++;

    if (timerCount % 3 == 0)
    {
        //Do tasks that should execute every 3 minutes
    }

    if (timerCount % 10 == 0)
    {
        //Do tasks that should execute every 10 minutes
    }
}
0
Scott Hannen On

Since users create these tasks, you'll have to store them somewhere, likely a database. The question doesn't specify how a user will define the task, but that's not really at the core of the question.

In your database you might have two tables. One is a definition of the task which includes the interval after which it should run. This could be stored in minutes or seconds depending on the expected use.

Another table would contain the history of executing those tasks. Each time a task is executed, store a new record. It might include the outcome as well.

Then, once per minute (or so) retrieve a list of tasks joined to the history to show the most recent execution for each task. One at a time, compare the last execution time to the interval. That's subtracting two date/times.

var minutesSinceLastExecution = (lastExecutionDateTime - DateTime.Now).TotalMinutes;
if (minutesSinceLastExecution >= minutesInterval)
    // execute the query

Then, after executing the query, insert a new history record.

That's a basic outline which still leaves a few questions unanswered. For example, could the time it takes a query to run be longer than the interval? Will you need to run unrelated queries simultaneously? You still have to figure out some details, and that could involve storing even more data. For example, you might want to indicate that a query is executing so that a subsequent interval doesn't start executing the same query. If you store that detail in your database as well then your process can scale across multiple servers if needed.