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

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.

Leave a Comment