Jump to content

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


Recommended Posts

Posted

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
Posted (edited)

 

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

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

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