日期:2014-05-18 浏览次数:20949 次
public class MyTimer {
public static class MyTask extends TimerTask{
/*
* 定时任务
*/
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("--------" + sdf.format(new java.util.Date()));
}
}
public static void main(String[] args){
Timer timer = new Timer();
//设置开始执行任务的时间
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 11);
cal.set(Calendar.MINUTE, 34);
cal.set(Calendar.SECOND, 0);
Date date = new Date();
date = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
Date now = new Date();
long interval = date.getTime() - now.getTime();
if (interval < 0) {
cal.add(Calendar.DAY_OF_MONTH, 1);
date = cal.getTime();
interval = date.getTime() - now.getTime();
}
System.out.println("the interval time is: " + interval);
//2013-10-05 11:34:00后执行定时执行任务,每两秒执行一次,开始执行任务的时间可以设置
timer.schedule(new MyTask(), interval, 2 * 1000);
}
}