1

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.

cnd
  • 32,616
  • 62
  • 183
  • 313

2 Answers2

1

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

See here for some details: Creating Scheduled Tasks

Community
  • 1
  • 1
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • But can I execute my code with it? I need to execute my code. – cnd Oct 30 '13 at 09:59
  • @Heather It works at the level of running an executable, so you'd write your executable and then set up the task to run your executable at a certain time. The advantage of using Windows Task Scheduler is that things will still run at the right time if the computer has been rebooted inbetween. – Matthew Watson Oct 30 '13 at 10:03
  • I think that there is https://github.com/quartznet/quartznet ( from link you provided ) that makes exactly what I need. – cnd Oct 30 '13 at 10:06
1

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();
}
Jacques Snyman
  • 4,115
  • 1
  • 29
  • 49