简体   繁体   中英

In Java, how do I execute code every X seconds?

I'm making a really simple snake game, and I have an object called Apple which I want to move to a random position every X seconds. So my question is, what is the easiest way to execute this code every X seconds?

apple.x = rg.nextInt(470);
apple.y = rg.nextInt(470);

Thanks.

Edit:

Well do have a timer already like this:

Timer t = new Timer(10,this);
t.start();

What it does is draw my graphic elements when the game is started, it runs this code:

@Override
    public void actionPerformed(ActionEvent arg0) {
        Graphics g = this.getGraphics();
        Graphics e = this.getGraphics();
        g.setColor(Color.black);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        e.fillRect(0, 0, this.getWidth(), this.getHeight());
        ep.drawApple(e);
        se.drawMe(g);

I would use an executor

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    Runnable toRun = new Runnable() {
        public void run() {
            System.out.println("your code...");
        }
    };
ScheduledFuture<?> handle = scheduler.scheduleAtFixedRate(toRun, 1, 1, TimeUnit.SECONDS);

Simplest thing is to use sleep .

        apple.x = rg.nextInt(470);
        apple.y = rg.nextInt(470);
        Thread.sleep(1000);

Run the above code in loop.

This will give you an approximate (may not be exact) one second delay.

You should have some sort of game loop which is responsible for processing the game. You can trigger code to be executed within this loop every x milliseconds like so:

while(gameLoopRunning) {
    if((System.currentTimeMillis() - lastExecution) >= 1000) {
        // Code to move apple goes here.

        lastExecution = System.currentTimeMillis();
    }
}

In this example, the condition in the if statement would evaluate to true every 1000 milliseconds.

Use a timer:

Timer timer = new Timer();
int begin = 1000; //timer starts after 1 second.
int timeinterval = 10 * 1000; //timer executes every 10 seconds.
timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
    //This code is executed at every interval defined by timeinterval (eg 10 seconds) 
   //And starts after x milliseconds defined by begin.
  }
},begin, timeinterval);

Documentation: Oracle documentation Timer

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