简体   繁体   中英

java scheduling task with timer at specific time

I have a database, from which I retrieve time of showing reminder (that is my task). The received time I put into timer, but it shows reminder not at this time but immediately at current time. What is the problem?

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

for example, the time of showing reminder is 17:10:00. but it shows at 17:00:00

First you have to get the timediffrence btween currentDatetime and reminderDatetime and get the milliseconds,then pass that millisecond in timer.schedule(new Task(),timediff) function. just like below ,

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;

}

your function

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM