简体   繁体   中英

Waiting two minutes to call a method

I'm working on a Minecraft Bukkit plugin, I know how to handle events and everything, but I'm not sure how to do this. I haven't actually written the code yet so here's a basic example of what I want to do:

public void playerDead() {  
    runCommand(commandHere)  
    //Wait 2 minutes.  
    runCommand(otherCommandHere 
}  

I just need the part to wait two minutes. Everything else is covered.

EDIT2: Seems I need to reset the delay to the beginning if someone else dies while it's going. Any suggestions?

Since I see you want to perform your action after the player has died. Then for sure you don't want to halt the main Thread with Thread.sleep(x);

What you can do is create a cooldown for the player that passed away.

public Map<String, Long> cooldown = new HashMap<String, Long>();

Long time = cooldown.get(player.getName());

if(time - System.currentTimeMillis() > 10*1000)
    cooldown.put(player.getName(), System.currentTimeMillis());

else
    int remains = (int)Math.floor(10 - System.currentTimeMillis());

Code reference here .


Or you can create your task to run like this:

Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() 
{
  public void playerDied() 
  {
    // Your code here.
  }
}, <delay in ticks>);

Get a reference to your plugin and pass it as the parameter plugin . Or if you are lazy just write it inside the plugin and pass it this .

You may try like this:

new Timer().schedule(new TimerTask() {          
    @Override
    public void run() {  
        runCommand(commandHere);
    }
}, 120000);

You should use the BukkitScheduler provided by Bukkit.

You have to save the BukkitTask object returned by the Scheduler.runTaskLater(...) method to use it later. Every time playerDead() is called, you can reset the delay by cancelling and restarting the task.

BukkitTask task;

public void playerDead() {
    // Command here
    if (task != null) {
        task.cancel();
    }
    task = getServer().getScheduler().runTaskLater(Plugin, new Task(), 2400L);
}

public class Task extends BukkitRunnable {
    @Override
    public void run() {
        // Other command here
        task = null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM