oh okay 6 Share Posted July 1, 2019 Lets say that I have a class called item.java and in the constructor I am starting a timer, is it possible to create multiple item objects and watch the timers and get notified when they have finished? I would love a snippet, thanks! Link to comment Share on other sites More sharing options...
numberkarl 3 Share Posted July 1, 2019 public int onLoop() { for(Item item : items) { if(item.expired()) { //Do whatever } } return 0; } class Item{ long expirationTime; public Item(long timer) { this.expirationTime = System.currentTimeMillis() + timer; } public boolean expired() { return System.currentTimeMillis() > expirationTime; } } So the simplest way is to just check in an update loop if the timer has expired and do whatever you want to at that point. An alternative, and probably the better option depending on what you're trying to do is a Timer + TimerTask. You set the amount of time to wait in the constructor. Then after that amount of time the run method in ItemTask will run on the given item. class Item{ Timer timer; public Item(int timer) { timer = new Timer("Item", true); timer.schedule(new ItemTask(this),timer); } } class ItemTask extends TimerTask{ Item item; public ItemTask(Item item) { this.item = item; } @Override public void run() { //Do whatever } } oh okay 1 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now