Search code examples
dvibed

Is there a way to run a task each day at a 8:00 AM in vibed?


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 ?


Solution

  • 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);
    }