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

前端 未结 5 1010
离开以前
离开以前 2020-11-28 08:33

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 discove

5条回答
  •  盖世英雄少女心
    2020-11-28 09:16

    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.

提交回复
热议问题