Search code examples
javatimerexecute

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);

Solution

  • Simplest thing is to use Thread.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.