Using Java Dates

Discussion in 'Spigot Plugin Development' started by WinAllDey, Apr 17, 2017.

  1. I have never used this before and was curious to know how to do it. What if I wanted to create a plugin where a certain command executed at a specific time (6:15 p.m for example)? Then would I have to check every second to see if the date matched?
  2. One solution would be to poll the time at specific intervals, yes. If you wanted something to happen somewhere in the time 6:15 you could poll for time every minute and still hit your mark. If you needed 6:15:00 exactly you would need to poll each second, yes. Thankfully that's not a huge deal and doesn't have a large performance impact (in relation to other things your plugin could be doing)
  3. Choco


    Use a Timer to execute a TimerTask at a specific Date. TimerTasks are similar to BukkitRunnables in that they have run() methods. Though, do keep in mind, if the server restarts, this Timer will not be kept in memory. Assure that the Date is being stored onDisable() and loaded onEnable() if it is going to be over a long period of time (i.e. multiple days) because servers often restart every 24 hours to clear any unused memory
    Code (Java):
    private static final Timer TIMER = new Timer();
    public void someMethod() {
        TIMER.schedule(new TimerTask() {
            public void run() {
                // Your logic to run at the specified date
        }, yourDateObject);
  4. Thank you everyone for the help.
    Whenever I restart the server, the date and time is still in memory. I've been testing it out a lot and when I schedule something to be run at say 6:15 and it is 6:00, I can restart the server as many times as I want and the task will still be run at 6:15.
    • Informative Informative x 1
  5. Choco


    Hm... That's interesting.. If the server is stopped it really shouldn't still be running. If you're just running /reload then yes, the JVM is still running. Eh... I'm no JVM expert and I can't even pretend to be one. If it works, it works I suppose
  6. Test it with PC restart :D Seriously though, I wouldn't count on that, better safe than sorry.
  7. I use this system in a AutoEvent plugin and it's work.Get the time from config make it date,make the diference of the real time and your data and transform all of the time in seconds(put 1 minute = 60 sec...)and after all of that execut an schedule with dilay with the time you put.
    • Agree Agree x 1
  8. Sounds like the time is hardcoded. If that's what you want, then it looks like you've got it!