Sunday, September 18, 2016

Simple Java Timer (Can be used in Android)

With the default fixed-period execution, each successive run of a task is scheduled relative to the start time of the previous run, so two runs are never fired closer together in time than the specified period. With fixed-rate execution, the start time of each successive run of a task is scheduled without regard for when the previous run took place. This may result in a series of bunched-up runs (one launched immediately after another) if delays prevent the timer from starting tasks on time.

// First run after 2000ms, next run after 1000ms
public static void testTimer() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
int i = 0;
public void run() {
Random rand = new Random();
int randInt5000 = rand.nextInt(5000);
System.out.println("working : " + randInt5000);
try {
} catch (InterruptedException e) {
// TODO Auto-generated catch block
if (i == 5) timer.cancel();

}, 2000, 1000);


No comments:

Post a Comment