如果你想简单地使用Timer,我会做这样的事情:
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
}
}
对不起,糟糕的身份。
另外,如果你需要安排执行代码,看看Guava Services,因为它真的可以使你的代码更清晰和抽象相当多的创建线程,调度等的样板。
顺便说一句,我没有产生随机数等的麻烦,但我想你可以弄清楚如何包含这个部分。我希望这足以让你走上正轨。
为了记录,如果你使用番石榴,它会是这样的:
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);
}
};
}
}
而您只需创建一个名为new CrawlingService.start()的主体;而已。