How to use Timer class to call a method, do something, reset timer, repeat?

chrisco picture chrisco · Feb 23, 2012 · Viewed 150.5k times · Source

I'm a Java beginner and have been futzing around with various solutions to this problem and have gotten myself kind of knotted up. I've tried with Threads and then discovered this Timer class and have messed around with it without success so far. If you could post executable code with a main method so I could see it working and start playing around from there, that would be great.

  1. Launch program
  2. call doSomething()
  3. Generate random number and set Timer for that long.
  4. When Timer goes off, call doSomething() again.

Probably using this: http://docs.oracle.com/javase/6/docs/api/java/util/Timer.html

Answer

pcalcao picture pcalcao · Feb 23, 2012

If you want to simply use Timer, I would do something like this:

public class TestClass {
    public long myLong = 1234;

    public static void main(String[] args) {
        final TestClass test = new TestClass();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                test.doStuff();
            }
        }, 0, test.myLong);
    }

    public void doStuff(){
        //do stuff here
    }
}

Sorry for the lousy identation.

Also, if you need to schedule execution of code, take a look at Guava Services since it can really make your code much clearer and abstract quite a bit of the boilerplate of creating threads, scheduling, etc.

By the way, I didn't take the trouble of generating random number, etc, but I think you can figure out how to include that part. I hope this is enough to get you on the right track.

For the record, if you were to use Guava, it would look something like this:

class CrawlingService extends AbstractScheduledService {

    @Override
    protected void runOneIteration() throws Exception {
        //run this alot
    }

    @Override
    protected void startUp() throws Exception {
        //anything you need to step up
    }

    @Override
    protected void shutDown() throws Exception {
        //anything you need to tear down
    }


    @Override
    protected Scheduler scheduler() {
        return new CustomScheduler() {
            @Override
            protected Schedule getNextSchedule() throws Exception {
                long a = 1000; //number you can randomize to your heart's content
                return new Schedule(a, TimeUnit.MILLISECONDS);
            }
        };
    }
}

And you would simply create a main that called new CrawlingService.start(); that's it.