chr*_*sco 28 java timer scheduled-tasks
我是一名Java初学者,并且已经为这个问题提供了各种解决方案,并且已经让我自己打结了.我已经尝试过使用Threads,然后发现了这个Timer类,并且到目前为止没有成功.如果您可以使用main方法发布可执行代码,那么我可以看到它正常工作并从那里开始玩,那将是很棒的.
doSomething()doSomething()再次呼叫.可能使用这个:http://docs.oracle.com/javase/6/docs/api/java/util/Timer.html
pca*_*cao 43
如果你想简单地使用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
}
}
Run Code Online (Sandbox Code Playgroud)
抱歉这个糟糕的身份.
此外,如果您需要安排代码执行,请查看Guava服务,因为它可以真正使您的代码更清晰,更抽象地创建线程,调度等等.
顺便说一句,我没有遇到生成随机数等问题,但我认为你可以弄清楚如何包含那部分.我希望这足以让你走上正轨.
为了记录,如果您使用Guava,它看起来像这样:
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);
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
你只需创建一个名为new CrawlingService.start()的main; 而已.
Sim*_*onC 25
你特意想要Timer吗?如果不是,你可能最好使用ScheduledExecutorService并调用scheduleAtFixedRate或scheduleWithFixedDelay; 引用Javadocs:
Java 5.0引入了
java.util.concurrent包,其中一个并发实用程序ScheduledThreadPoolExecutor是一个线程池,用于以给定的速率或延迟重复执行任务.它实际上是Timer/TimerTask组合的更通用的替代品 ,因为它允许多个服务线程,接受各种时间单位,并且不需要子类化TimerTask(只是实现Runnable).ScheduledThreadPoolExecutor使用一个线程进行配置使其等效于Timer.
UPDATE
这是一些使用的工作代码ScheduledExecutorService:
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) {
final ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
System.out.println(new Date());
}
}, 0, 1, TimeUnit.SECONDS);
}
}
Run Code Online (Sandbox Code Playgroud)
输出如下:
Thu Feb 23 21:20:02 HKT 2012
Thu Feb 23 21:20:03 HKT 2012
Thu Feb 23 21:20:04 HKT 2012
Thu Feb 23 21:20:05 HKT 2012
Thu Feb 23 21:20:06 HKT 2012
Thu Feb 23 21:20:07 HKT 2012
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
134558 次 |
| 最近记录: |