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.
doSomething()
doSomething()
again.Probably using this: http://docs.oracle.com/javase/6/docs/api/java/util/Timer.html
Use timer. scheduleAtFixedRate() to schedule it to recur every two seconds: Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.
Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With