timer基础问题

chensiyu04 2008-02-16 02:55:57
我想让 timer在
早上6:00 中午12点 晚上18:00
运行
schedule(TimerTask task, Date time)


我该怎么写?
...全文
51 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Acylas 2008-02-16
  • 打赏
  • 举报
回复
这个问题容易解决,对Date进行计算转换一下就ok了.
TimerTask task = new TimerTask(){
public void run() {
//To do
}
}
Timer timer = new Timer();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = sdf.pasre("2008-02-16 6:00");
Calendar currentTime = Calendar.getInstance();
Calendar firstTime = Calendar.getInstance();
if (date < currentTime.getTimeInMillis()) {
firstTime.set(currentTime.get(Calendar.YEAR),currentTime.get(Calendar.MONTH),
currentTime.get(Calendar.DATE));
//如果当前的时间已经超过了指定运行的时间,则要重新设定运行时间
if (firstTime.getTimeInMillis() <= currentTime.getTimeInMillis()) {
while (firstTime.getTimeInMillis() <= currentTime.getTimeInMillis()) {
long exeTime = firstTime.getTimeInMillis() + 1000 * 60 * 60 * 6;
firstTime.setTime(new Date(exeTime));
}
}
else {
while (firstTime.getTimeInMillis() - currentTime.getTimeInMillis() > 1000 * 60 * 60 * 6) {
long exeTime = firstTime.getTimeInMillis() - 1000 * 60 * 60 * 6;
firstTime.setTime(new Date(exeTime));
}
}
}
else {
firstTime.setTime(date);
}

timer.schedule(task, firstTime.getTime(), 1000 * 60 * 60 * 6);//每隔六小时运行一次

建议不要用java本身的Timer,这是通过Object的wait等方法进行控制的,
如果有多个TimerTask的时候,不能同步触发.最好是用Quartz.


chensiyu04 2008-02-16
  • 打赏
  • 举报
回复
...分给过你才发现问题还没解决..

timer.schedule(task, date, 1000 * 60 * 60 * 6);//每隔六小时运行一次
你这是每间隔6个小时才运行一次
如果中间程序关闭了呢??? 那不就完蛋了?
我要的是
早上6:00 中午12点 晚上18:00
chensiyu04 2008-02-16
  • 打赏
  • 举报
回复
thanks you!
分已给你`
Acylas 2008-02-16
  • 打赏
  • 举报
回复
TimerTask task = new TimerTask(){
public void run() {
//To do
}
}
Timer timer = new Timer();
Date date = SimpleDateFormat.pasre("2008-02-16 6:00");
timer.schedule(task, date, 1000 * 60 * 60 * 6);//每隔六小时运行一次

62,629

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧