How to call function every hour? Also, how can I loop this?

前端 未结 4 1107
鱼传尺愫
鱼传尺愫 2021-02-05 14:17

I need a simple way to call a function every 60 minutes. How can I do this? I\'m making a MineCraft bukkit plugin, and this is what I have:

package com.webs.play         


        
相关标签:
4条回答
  • 2021-02-05 14:17

    Create a Timer object and give it a TimerTask that performs the code you'd like to perform.

    Timer timer = new Timer ();
    TimerTask hourlyTask = new TimerTask () {
        @Override
        public void run () {
            // your code here...
        }
    };
    
    // schedule the task to run starting now and then every hour...
    timer.schedule (hourlyTask, 0l, 1000*60*60);
    

    If you declare hourlyTask within your onPlayerInteract function, then you can access l1 and l2. To make that compile, you will need to mark both of them as final.

    The advantage of using a Timer object is that it can handle multiple TimerTask objects, each with their own timing, delay, etc. You can also start and stop the timers as long as you hold on to the Timer object by declaring it as a class variable or something.

    I don't know how to get every block in between.

    0 讨论(0)
  • 2021-02-05 14:20

    Create a thread that will run forever and wakes up every hour to execute your data.

    Thread t = new Thread() {
        @Override
        public void run() {
            while(true) {
                try {
                    Thread.sleep(1000*60*60);
                    //your code here...
                } catch (InterruptedException ie) {
                }
            }
        }
    };
    t.start();
    
    0 讨论(0)
  • 2021-02-05 14:20

    You must use Bukkit Scheduler:

    public void Method(){
        this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
            @Override
            public void run() {
                // Your code goes here
                Method();
            }
        }, time * 20L );
    }
    

    You must create a method with this and there you must call the same method.

    0 讨论(0)
  • 2021-02-05 14:21
    1. The simplest way (in my opinion) is use Thread (the above comment has mention about it).
    2. You can also use Timer in javax.swing.Timer
    3. But i think - as 101100 said - you can use TimerTask. You can check this link (from IBM)
    0 讨论(0)
提交回复
热议问题