关于java:Java里的定时任务

39次阅读

共计 1157 个字符,预计需要花费 3 分钟才能阅读完成。

办法调用

try {
    // 每天 12 点执行定时工作
    timing("12:00:00");
} catch (ParseException e) {e.printStackTrace();
}

办法体



/**
* @param time 每天几点执行定时工作   24 小时制工夫 例: 08:00:00  20:00:00
* @throws ParseException
*/
private void timing(String time) throws ParseException {int hour = Integer.parseInt(time.substring(0, 2));
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 获取以后小时
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    int currentHour = calendar.get(Calendar.HOUR_OF_DAY);

    long delayTime;
    long currentTime = System.currentTimeMillis();

    if (currentHour < hour) {
    // 延时工夫 = 当天 8 点 - 以后工夫
    String currentDay = format1.format(new Date());
    long currentDay8 = format2.parse(currentDay + " " + time).getTime();
    delayTime = currentDay8 - currentTime;
    } else if (currentHour == hour) {delayTime = 0;} else {
        // 延时工夫 = 今天 8 点 - 以后工夫
        Date date = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, 1);
        String nextDay = format1.format(c.getTime());
        long nextDay8 = format2.parse(nextDay + " " + time).getTime();
        delayTime = nextDay8 - currentTime;
    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {//TODO 执行工作}
    };

    Timer timer = new Timer(true);
    timer.schedule(task, delayTime, 24 * 60 * 60 * 1000);
    }

正文完
 0