定时任务的实现方式
定时任务的实现有3种方式:①while死循环 ②linux crontab ③Java TimerTask
以后补充
③还有一种不精确的方法是TimerTask。
1 TimerTask task = new TimerTask() { 2 @Override 3 public void run() { 4 //do something 5 } 6 }; 7 Timer t = new Timer(); 8 t.scheduleAtFixedRate(task, 60000, 60000);
对scheduleAtFixedRate方法的解释:Timer.class的源码是这样写的。
long delay是启动这个定时任务的延迟:System.currentTimeMillis()+delay;
long period是between successive task executions.成功执行后,过period时间,再次执行一次定时任务。
1 /* 2 * @param task task to be scheduled. 3 * @param delay delay in milliseconds before task is to be executed. 4 * @param period time in milliseconds between successive task executions. 5 * @throws IllegalArgumentException if <tt>delay</tt> is negative, or 6 * <tt>delay + System.currentTimeMillis()</tt> is negative. 7 * @throws IllegalStateException if task was already scheduled or 8 * cancelled, timer was cancelled, or timer thread terminated. 9 */ 10 public void scheduleAtFixedRate(TimerTask task, long delay, long period) { 11 if (delay < 0) 12 throw new IllegalArgumentException("Negative delay."); 13 if (period <= 0) 14 throw new IllegalArgumentException("Non-positive period."); 15 sched(task, System.currentTimeMillis()+delay, period); 16 }
posted on 2014-03-17 16:22 BYRHuangQiang 阅读(702) 评论(0) 编辑 收藏 举报