Question

I mean I want to make something: for example tomorrow at 6 a.m. ( clock based event )

For now the only variant I see is starting new timer with TimpeStamp from FutureTime - Now

But this solution looks ugly, specially when I will have many events it will force me to have many timers or somehow make timer process nearly event first and then re-calculate how long to wait on next event. And re-calculate each time when I will push new event to events collection.

Just asking if there is something more sane compared to my solution? Or maybe if there is already some free-for-use lib for it.

Was it helpful?

Solution

It's probably better to use the Windows Task Scheduler for this.

See here for some details: Creating Scheduled Tasks

OTHER TIPS

You can create 1 timer to execute every x seconds and iterate over an array of events and check if it needs to execute.

If an event must execute, execute it on a separate thread to ensure it does not interrupt the timer thread.

Event class

class Event
{
    DateTime TargetDate;
    bool Completed = false;
    IExecuter Executer;
}

The IExecuter inteface

interface IExecuter
{
    void Execute();
}

Sample IExecuter implementation

class LogEvent : IExecuter
{
    void Execute(){
         // Log event details to DB or Console or whatever
    }
}

Sample timer loop

foreach (Event e in eventArr)
{
    if(e.TargetDate == DateTime.Now && !e.Completed)
        e.Executer.Execute();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top