如何使用Timer设置定时任务?
在我的应用程序中,我想在每天午夜加载一些数据到数据库,如何使用计时器设置它?
我曾想过使用:
Timer t=new Timer();
TimerTask tt=new TimerTask(){
public void run(
//read the data, and push to db
);
};
t.schedule(tt,(the next midnight-now time));
但是,恐怕这只能执行一次。有什么解决办法吗?
In my application,I want load some data to the database at the midnight each day,how to set it using the Timer?
I have thought using:
Timer t=new Timer();
TimerTask tt=new TimerTask(){
public void run(
//read the data, and push to db
);
};
t.schedule(tt,(the next midnight-now time));
However, I am afraid this can only be executed once. Any fix?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能需要使用 public void ScheduleAtFixedRate(TimerTask task, Date firstTime, long period)
安排指定任务从指定时间开始重复固定速率执行。随后的执行大约以固定的时间间隔进行,并以指定的时间段分隔。
http://download.oracle.com/javase /1.4.2/docs/api/java/util/Timer.html
You might want to use
public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
Schedules the specified task for repeated fixed-rate execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html
您可能想查看 QuartzScheduler。它在复杂的计时过程中非常有用。它也非常容易使用。
由于您的任务非常简单,因此您可能不想使用额外的库,但请记住这一点。
http://www.quartz-scheduler.org/
You may want to check QuartzScheduler out. It is very useful in complex timing processes. It is also very easy to use.
Since your task is a very simple one, you may not want to use an extra library, but keep that in your mind.
http://www.quartz-scheduler.org/