1

I'm trying to run a task each day at 8:00 AM in a vibe.d web app. For the moment, I use the setTimer function with the periodic parameter to true. But this way, I can't control exactly the hour at which the task will be triggered. Is there an easy way to do this in vibed ?

moppag
  • 956
  • 9
  • 17
  • 2
    Nothing prevents you from calculating time until next 8:00 AM and calling `setTimer` with proper duration. – sigod Apr 11 '17 at 13:49

1 Answers1

2

Thank you sigod, that is exactly what I've done. I calculate the time until next 8:00 AM and call setTimer. Here is the code for further reference:

void startDailyTaskAtTime(TimeOfDay time, void delegate() task) {
  // Get the current date and time
  DateTime now = cast(DateTime)Clock.currTime();

  // Get the next time occurrence
  DateTime nextOcc = cast(DateTime)now;
  if (now.timeOfDay >= time) {
    nextOcc += dur!"days"(1);
  }
  nextOcc.timeOfDay = time;

  // Get the duration before now and the next occurrence
  Duration timeBeforeNextOcc = nextOcc - now;

  void setDailyTask() {
    // Run the task once
    task(); 
    // Run the task all subsequent days at the same time
    setTimer(1.days, task, true);
  }

  setTimer(timeBeforeNextOcc, &setDailyTask);
}
moppag
  • 956
  • 9
  • 17