java 调用定时器的方法_java – 如何使用Timer类调用方法,做某事,重置定时器,重复?...

如果你想简单地使用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()的主体;而已。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值