栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java月度计时器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java月度计时器

如果您担心要创建不需要的对象,则可以始终创建一个对象,该对象又会创建/“销毁”所有引用,因此可以对创建的对象进行通用控制。

在最坏的情况下,一年中将有12个不需要的对象,我认为这是可以承受的。您的担心仍然有效。

这是我在执行死刑后按照乔尔的时间表建议进行的尝试。注意,当前的Timer被新的Timer取代,因此,可以对timer和timer任务进行gc’ed操作。

package monthly.schedule;import java.util.Timer;import java.util.TimerTask;import java.util.Date;import java.util.Calendar;public class MonthlyTimer {     // What to do    private final Runnable whatToDo;    // when     private final int dayOfMonth;    private final int hourOfDay;    // The current timer    private Timer current = new Timer();//to avoid NPE    public void cancelCurrent() {         current.cancel();// cancel this execution;        current.purge(); // removes the timertask so it can be gc'ed    }    // create a new instance    public static MonthlyTimer schedule( Runnable runnable, int dayOfMonth, int hourOfDay ) {         return new MonthlyTimer( runnable, dayOfMonth, hourOfDay );    }    private MonthlyTimer(Runnable runnable, int day, int hour ) {         this.whatToDo = runnable;        this.dayOfMonth = day;        this.hourOfDay = hour;        schedule();    }    // Schedules the task for execution on next month.     private void schedule() {         // Do you mean like this?        cancelCurrent();        current = new Timer(); // assigning a new instance        // will allow the previous Timer to be gc'ed        current.schedule( new TimerTask() {  public void run() {      try {          whatToDo.run();     } finally {          schedule();// schedule for the next month     } }        } , nextDate() );    }    // Do the next date stuff    private Date nextDate() {         Calendar runDate = Calendar.getInstance();        runDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);        runDate.set(Calendar.HOUR_OF_DAY, hourOfDay);        runDate.set(Calendar.MINUTE, 0);        runDate.add(Calendar.MONTH, 1);//set to next month        return runDate.getTime();    }}class UseIt {     public static void main( String [] args ) {         int the1st = 1;        int at16hrs = 16;        MonthlyTimer t = MonthlyTimer.schedule( new Runnable() {  public void run() {      System.out.println( "Hola" ); }}, the1st, at16hrs );        // will print "Hola" every 1st at 16:00 hrs.       // if needed you can cancel with:         t.cancelCurrent();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/570759.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号