【问题标题】:java scheduling task with timer at specific timejava在特定时间使用计时器调度任务
【发布时间】:2014-07-08 15:03:29
【问题描述】:

我有一个数据库,我从中检索显示提醒的时间(这是我的任务)。我将收到的时间放入计时器,但它不是在此时显示提醒,而是在当前时间立即显示。有什么问题?

rs = stmt.executeQuery(sql);
while(rs.next()){
   time=rs.getString   ("time");
}
timer = new Timer(); // Instantiate Timer Object
timer.schedule(new Task(), timeFormat.parse(time));

例如,显示提醒的时间是 17:10:00。但它显示在 17:00:00

【问题讨论】:

  • 看起来缺少日期信息,因此默认为空白日期(可能是 1970 年 1 月 1 日),这意味着计时器将立即运行任务。 timeFormat 是什么?它是SimpleDateFormat 对象吗?另外,您从数据库中获得的 time 字符串是什么?尝试在数据库中存储一个实际的TIMESTAMP 并改用rs.getDate(String)
  • 非常感谢。问题与您写的完全一样(解析时间后,日期自动变为 01.01.1970)。通过连接提醒的实际日期(它存储在我的数据库中的单独列中)及其时间来解决它,所有这些我都像字符串一样检索。只有在那之后,我才使用 SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 进行解析,并将结果设置到我的计时器中。

标签: java timer


【解决方案1】:

首先你必须得到当前日期时间和提醒日期时间之间的时间差异并得到毫秒,然后在 timer.schedule(new Task(),timediff) 函数中传递那个毫秒。 就像下面一样,

private long ScheduleTime(String strpostDate) {

    long hrs = 0;
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    Date curDate = null;
    Date postDate = null;
    String curdate = formatter.format(new Date());
    try {
        curDate = (Date) formatter.parse(curdate);
        postDate = (Date) formatter.parse(strpostDate);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    long diffInMs = postDate.getTime() - curDate.getTime();
    return diffInMs;

}

你的功能

rs = stmt.executeQuery(sql);
while(rs.next()){
datetime=rs.getString   ("time");
}
timer = new Timer(); // Instantiate Timer Object
timer.schedule(new Task(), ScheduleTime(datetime));

【讨论】:

  • Timer.schedule(TimerTask task, Date time) 怎么样?当然,如果你有Date,你可以将它传递给这个方法并让Timer 类在内部管理延迟计算......对吗?
  • 请查看此链接,您可能会从中得到答案,java2s.com/Code/Java/Development-Class/…
  • 我的问题是如果你可以构建一个Date 对象,你为什么不直接将它传递给我引用的schedule 方法呢?您不需要获取系统日期并计算毫秒延迟。事实上,尝试在您的 ScheduleTime 方法中返回 postDate 看看会发生什么!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 2015-07-14
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多