Best way to do this (Loops)

Discussion in 'Plugin Development' started by HeadGam3z, Jun 7, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    HeadGam3z

    I needed to make a loop so that a value gets decreased by one every one second, instead of the usual decrease by one every extremely-fast-second. So I used this:
    Code:java
    1. while (delayLeft > 0) {
    2.  
    3. try {
    4. Bukkit.broadcastMessage("Delay is set for " + delayLeft + " second(s)!");
    5. Thread.sleep(1 * 1000);
    6. delayLeft--;
    7. } catch (InterruptedException e) {
    8. e.printStackTrace();
    9. }
    10.  
    11. }
    12. Bukkit.broadcastMessage("Delay success!");
    13. return true;

    Which would do exactly what I wanted, so great (yay me.) But here's my question:
    What is the best way of decreasing a value by one every one second in your opinion?

    Edit: this isn't so much a Bukkit thing, as this would obviously pause the entire server. lol
     
  2. Offline

    Mrawesomecookie

    HeadGam3z
    If you use Thread.Sleep the server will shoot itself. Try using the bukkit scheduler.
     
    teej107 likes this.
  3. Offline

    HeadGam3z

    Mrawesomecookie
    I guess you didn't read my edit? ._. More of a java question than Bukkit.
     
  4. Offline

    Maurdekye

    HeadGam3z Thing is, you're asking the wrong question; partially. How exactly you go about it is entirely dependent on what you're writing the code for.
    If you're only writing a single, stand-alone java program that doesn't do anything else while you're waiting, then that's probably the best method you have above.
    If you're going to have other parts of the program running while this part waits, then you'd need to put those parts on a separate thread, and run those while this thread sleeps.
    Again, it always depends. There are many ways to do one thing, but there's usually a best/fastest/easiest/accepted method that you should be using 90% of the time. In your case, Thread.sleep is just fine.

    Also, this is the Bukkit forum, not a general Java forum. If you want help with Java, ask at StackOverflow. You won't often find people as generous who will be willing to answer your question here.
     
Thread Status:
Not open for further replies.

Share This Page