Run every day at midnight

Discussion in 'Plugin Development' started by martijnpold, Sep 16, 2015.

Thread Status:
Not open for further replies.
  1. I'm creating a plugin that requires a piece of code to be ran once every day at midnight, how would i set this up?
     
  2. Offline

    teej107

  3. Offline

    teej107

    This link can give you everything you need to know about getting the current time.
     
  4. @teej107 I know how to do that but I don't know how to use that to time the code
     
  5. Offline

    MCnumi

    Code:
    Calendar.get(Calendar.MINUTE)
    use it like that. or change the MINUTE to whatever you like.
     
  6. Offline

    teej107

    @martijnpold you'll need a task to run every minute (or longer depending on accuracy) to see if it is midnight/past midnight
     
  7. Offline

    Zombie_Striker

    @martijnpold
    Try Something like this:
    Code:
    int DAY = -1;
    
    // Make a repeating task. This can be every second if you want it to be precise, or every minute/hour if you want to save memory.
       public void run(){
       if(DAY < 0)
          DAY = Calander.DAY;//DAY will be equal to what day it is on sever start-up
        if(DAY < Calander.DAY){//If the day has changed
           DAY = Calander.DAY;
          //Do Stuff
       }
    }
     
  8. Offline

    pedrinholuizf

    Try to put this into your code:
    Code:
        public static int scheduleRepeatAtTime(Plugin plugin, Runnable task, int hour)
        {
           Calendar cal = Calendar.getInstance();
           cal.setTimeZone(TimeZone.getTimeZone("GMT-04:00"));
           long now = cal.getTimeInMillis();
           if(cal.get(Calendar.HOUR_OF_DAY) >= hour)
               cal.add(Calendar.DATE, 1);
           cal.set(Calendar.HOUR_OF_DAY, hour);
           cal.set(Calendar.MINUTE, 0);
           cal.set(Calendar.SECOND, 0);
           cal.set(Calendar.MILLISECOND, 0);
           long offset = cal.getTimeInMillis() - now;
           long ticks = offset / 50L;
           return Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, task, ticks, 1728000L);
        }
    
    And then use it like this:
    Code:
    scheduleRepeatAtTime(this, new Runnable() {
               public void run()
               {
                    //YOUR CODE HERE
               }
           }, 0); // THE HOUR OF THE DAY
    
     
    DoggyCodeâ„¢ likes this.
  9. Offline

    boomboompower

    Do not spoonfeed, it really doesn't help on the forums.
     
Thread Status:
Not open for further replies.

Share This Page