转载:http://blog.sina.com.cn/s/blog_6d0730c70100y9gf.html
import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import sun.util.calendar.CalendarUtils; public class A { static int count = 0; public static void main(String[] args) { operateOnTime(); } public static void operateOnTime(){ //定时执行的任务 TimerTask task = new TimerTask(){ public void run(){ //在此代码内调用要执行任务的代码 System.out.println("时间=="+new Date()+"第"+ ++count+"次执行"); } }; //创建一个定时器 Timer timer = new Timer(); //设置执行时间 Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH);//每天 //定制每天的21:09:00执行 c.set(year, month,day,15,29,00); Date date = c.getTime(); System.out.println("==="+date); int p = 2*1000; //每天的date时刻执行task ,每隔2秒重复执行 // timer.schedule(task, date,p); //每天的date时刻执行task,仅执行一次 timer.schedule(task, date); } }