Jump to content

How to implement an action after a random amount of time has passed


Lewis

Recommended Posts

long lastHop = System.currentTimeMillis();

if(lastHop >= (pastTime + 30*60000) { //multiply by 60000 to get mins

doSomething();

}

 

like this? is what i can find, but its after a set amount of time rather than random between two ints

 

I'm not trying to berate you or anything but I really think it would benefit you greatly to learn the basics first, all of this trivial you should be able to come up with the solution on your own after just an hour of reading or even less.

 

  • Like 2
Link to comment
Share on other sites


 

private Timer worldHoppingTimer = new Timer();

public int onLoop() {

if (worldHoppingTimer.isActive()) {

//do something here

int hour = 3600000;

int minHours = 1 * hour;

int maxHours = 3 * hour;

worldHoppingTimer.setTimeout(random(minHours, minHours)); //set the timer to go off in 1 - 3 hours (just an example)

}

return 100;

}


 

public class Timer {

private long timeout;

public Timer() {

timeout = System.currentTimeMillis();

}

public boolean isActive() {

return timeout > System.currentTimeMillis();

}

public void setTimeout(long timeout) {

this.timeout = timeout + System.currentTimeMillis();

}

public long getElapsedTime() {

return System.currentTimeMillis() - timeout;

}

public String getElapsedToString() {

return Format.msToString(getElapsedTime());

}

public long getPerHour(long value) {

return value * 3600000 / getElapsedTime();

}

}

Edited by Easy
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...