2012-08-07 48 views
2

我想在一段時間後觸發一個動作,我一直在Google上如何做,但我沒有運氣,我想這只是我的遊戲編碼方式。 無論如何,我需要在代碼a1觸發後30分鐘後觸發代碼a2。Java定時觸發器

A1:

if (itemId == 608) { 
     c.sendMessage("The scroll has brought you to the Revenants."); 
     c.sendMessage("They are very ghastly, powerful, undead creatures."); 
     c.sendMessage("If you defeat them, you may receive astounding treasures."); 
     c.sendMessage("If you donate you may visit the Revenants anytime without a scroll."); 
     c.getPA().movePlayer(3668, 3497, 0); 
     c.gfx0(398); 
     c.getItems().deleteItem(608, 1); 
} 

A2:

c.getPA().movePlayer(x, y, 0); 
+1

你肯定* * [RUNESCAPE](http://www.rune-server.org/runescape-development/rs2-server/downloads/283605-project- insanity.html)是你的遊戲嗎? – oldrinb 2012-08-07 01:52:58

+0

你想要計時器有多準確? – MadProgrammer 2012-08-07 01:58:30

回答

1

由於該代碼使用Project Insanity,你應該使用內置的調度事件設施由server.event.EventManager提供。

下面是示例代碼:

if (itemId == 608) { 
    c.sendMessage("The scroll has brought you to the Revenants."); 
    c.sendMessage("They are very ghastly, powerful, undead creatures."); 
    c.sendMessage("If you defeat them, you may receive astounding treasures."); 
    c.sendMessage("If you donate you may visit the Revenants anytime without a scroll."); 
    c.getPA().movePlayer(3668, 3497, 0); 
    c.gfx0(398); 
    c.getItems().deleteItem(608, 1); 

    /* only if the parameter Client c isn't declared final */ 
    final Client client = c; 
    /* set these to the location you'd like to teleport to */ 
    final int x = ...; 
    final int y = ...; 

    EventManager.getSingleton().addEvent(new Event() { 

    public void execute(final EventContainer container) { 
     client.getPA().movePlayer(x, y, 0); 
    } 
    }, 1800000); /* 30 min * 60 s/min * 1000 ms/s = 1800000 ms */ 
} 
+1

(+1)用於識別框架並提出框架原生方法。 – harschware 2012-08-07 02:17:53

2

有很多方法可以做到計時器在Java中,但自我介紹到一個很好的框架退房http://quartz-scheduler.org/。如果你使用它,Spring也有石英集成。

但更重要的是,如果你正在創建一個遊戲,你需要遊戲編程的核心技術叫做event loop

這似乎是的how to create a game architecture

+0

謝謝。我會試試這個。 – 2012-08-07 01:51:17

+0

請務必再次閱讀。我做了編輯... – harschware 2012-08-07 01:57:50

1

可以使用了Thread.sleep一個體面的討論()但如果您在主線程中調用應用程序,它會凍結您的應用程序,因此,請創建另一個線程並將代碼放入其中。這樣做你不會停止主應用程序。

這是一個簡單的例子。

public class MyThread implements Runnable { 

    @Override 
    public void run() { 

     try { 

      System.out.println("executing first part..."); 
      System.out.println("Going to sleep ...zzzZZZ"); 

      // will sleep for at least 5 seconds (5000 miliseconds) 
      // 30 minutes are 1,800,000 miliseconds 
      Thread.sleep(5000L); 

      System.out.println("Waking up!"); 
      System.out.println("executing second part..."); 

     } catch (InterruptedException exc) { 
      exc.printStackTrace(); 
     } 

    } 

    public static void main(String[] args) { 
     new Thread(new MyThread()).start(); 
    } 

} 

這將只運行一次。要運行多次,您需要一個包含run方法體的無限循環(或由一個標誌控制的循環)。

你有一些其他選項,如: