2012-08-07 42 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方法体的无限循环(或由一个标志控制的循环)。

你有一些其他选项,如: