Reputation: 61
So, I am programming this Minecraft bukkit plugin, and I want some help with how to make the plugin wait for a specific amount of time before executing a line of code. Because if we try this:
Thread.sleep(4000);
That will actually pause the entire server for 4 seconds...
So I want a code which can be used in Bukkit, and not freeze the entire server. Here's my code:
@EventHandler
public void bombSymptom (PlayerInteractEvent event) throws InterruptedException{
final Player player = event.getPlayer();
if (player == Bukkit.getPlayer("Viktoracri") && event.getItem() != null && event.getItem().getType() == Material.PUMPKIN && player.isOnGround() && player.getHealth() == 20){
Location loc = event.getPlayer().getLocation();
player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 100, 10));
event.getPlayer().getWorld().createExplosion(loc, 3);
player.setHealth(15);
//Wait 1 sec
player.setHealth(16);
//Wait 2 sec
player.setHealth(17);
//Wait 1 sec
player.setHealth(18);
//Wait 1 sec
player.setHealth(19);
}
}
Can somebody please give me a code on how to do this? I would very much appreciate that.
Upvotes: 0
Views: 7477
Reputation: 1303
You could make a thread, which would basically run along side the server. You would setup the thread class like this:
public class BombThread implements Runnable {
public Player p;
public BombThread (Player p) {
this.p = p;
}
public void run() {
p.setHealth(15);
Thread.sleep(1000);
p.setHealth(16);
Thread.sleep(2000);
p.setHealth(17);
Thread.sleep(1000);
p.setHealth(18);
Thread.sleep(1000);
p.setHealth(19);
}
}
Then to run it, in your listener method, you would do:
BombThread thread = new BombThread(player);
thread.start();
Upvotes: 0
Reputation: 161
The reason thread.sleep(int) crashes your server is it freezes your servers thread making the program stop due to inactivity(Somthing like this you get the idea).
You can use bukkit schedulars! Or if you want to do somthing more advanced and faster than bukkit you can use normal threads(Just make sure to create a new one with thread.start())
You can use either of these to count from 15 to 19 with a 1 second delay. Or count from 0 to 4 and set the health to the number + 15.
For this we don't need to go faster than minecraft so we can use bukkit schedulars. Schedular Info
final int run = Bukkit.getScheduler().scheduleSyncRepeatingTask(Core.getPlugin(), new Runnable()
{
int i = 0;
@Override
public void run()
{
if (i > 4)
Bukkit.getScheduler().cancelTask(run);
player.setHealth(i + 15);
i++;
}
}, initDelay, loopDelay);
Init delay is the delay in ticks before it starts. Loop delay is the delay in ticks between iterations.
Remember there are 20 ticks in a second so for you it would be 0 for init delay and 20 for loop delay.
If you really do need to have the delay to change you can keep it at one second and wait an extra iteration before continuing.
Upvotes: 3