Solved Timer for every player

Discussion in 'Spigot Plugin Development' started by Dubbly, Mar 8, 2018.

  1. Hello,

    I'm trying to make a method. If you hit a player it would place him and the murderer into a hashmap. I want to create a timer, which runs after a player was hit. And for example after 20 seconds the timer will stop and the player will be deleted from the hashmap. But when the player will be hit another time. The old timer would be canceled and a new one will be started.

    I have only one question is there a way to create for every player their own timer? If yes, then how?

    Thank you
  2. Listen for the EntityDamageByEntityEvent, check if both entities are players, if the damager is not in the map, create a new instance of a BukkitRunnable (I do suggest you to create a new class that extends bukkit runnable, i try to avoid anonymous classes) and save the BukkitTask or that instance in the Map?
    • Agree Agree x 1
  3. What Parozzz said, or you can make only 1 runnable and control all timers in that 1 runnable by having 2 hashmaps, both of them storing the UUID of the killer as the key, but the value for one will be the unix time stamp of when the timer should expire, and the other should store the targetee.

    Any reason your doing this? Maybe a better example could be given.
    • Agree Agree x 1
  4. Why avoid anonymous classes?
    Also I recommend using BukkitScheduler + lambdas, especially for tasks that don't need canceling :)
  5. Anonymous classes require all fields used inside to be final when you can make custom classes and they wont need to be final.
  6. I'm guessing you are making an anti pvp logger system, Use System#currentTimeMillis. Everytime a player logs out check if they are in the map. If they are, then get current time minus the time from the map(current time - last hit time). if that is bigger than 20,000, then they logged before their pvp timer has ended. Having multiple runnables seems weird imo.

    EDIT: You could have a timer run every minute to remove all outdated times, but that isn't truly necessary.
    • Agree Agree x 1
    • Winner Winner x 1
  7. Indeed. But it sure beats creating an in method (or worse not in method) class if you ask me :D
  8. Yeah, I came to a solution. I just used two Hashmaps, one for <target, killer> and one <target, time>. I just made a BukkitRunnable, that does -1 by every entry<target, time> when it's by 0. it will delete this target key from both hashmaps.

    No, I am working on a knockout mini-game, so when the timer runs out the lastDamager doesn't recive a kill, because the victim killed itself... for example.
  9. You can set the time the player was hit in the HashMap using System.getCurrentTimeMillis() and then when they die just take the current time and subtract it from the time they were hit to get the elapsed time. (note that currentTimeMillis gets the current time in milliseconds, not seconds)

Share This Page