我想从2013年9月30日开始,每隔一个月重复执行一个函数,请问用java的Timer计时器应该怎么写?
------解决方案--------------------
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);
}
}