-1

I need to repeat a task every 5 seconds in java, I'm creating a minecraft bukkit / spigot Plugin, so doing it with Java or using the bukkit api would both work great.

Code:

public void onEnable(){
            getLogger().info("TBC Enabled");
            
            //~~ the statement from here till the next note is what I want to happen every 5 seconds
            
            for (Player player : Bukkit.getOnlinePlayers()) {
                player.sendMessage("N/A");
            }
            
            //~~ end of statement I want to repeat every 5 seconds
            
            }

Thanks for the help!

Cheap CPPS
  • 49
  • 1
  • 8

2 Answers2

2

You can do what is called scheduling a repeating task, this example was pulled from the Bukkit forums.

Bukkit.getScheduler().scheduleRepeatingTask(this, new Runnable() {
    @Override
    public void run() {
        // The statement you want to run every 5 seconds.
    }
}, 0L, 100L); // 20 ticks = 1 second

Simply edit the comment in run with the statement you want to run and it should work fine.

JustTalz
  • 46
  • 3
1

This can be done with a basic ExecutorService. You can create a ScheduledExecutorService which is an implementation of ExecutorService and then schedule a runnable which executes every 5 seconds.

        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

        service.scheduleAtFixedRate(() -> {
            //TODO do something here
        }, 0, 5, TimeUnit.SECONDS);
Jason
  • 5,154
  • 2
  • 12
  • 22