自我过期对象在Java中(Timertask)

huangapple go评论77阅读模式
英文:

Selfexpiring object in java (Timertask)

问题

我有一个需求,需要编写一个实现,在特定时间后,类/对象会自动过期。目前,我已经扩展了TimeTask类,它在预定的时间调用一个类中的run方法,并执行所需的下游服务调用。 (我的示例代码如下)

我不确定TimerTask是否是一个高效的解决方案。有人能否分享一下他们对TimerTask的看法,以及是否有比TimerTask更好的方法?

public class SelfExpiringTask extends TimerTask {

    private List<String> updatedList;
    private Timer timer = new Timer();

    public SelfExpiringTask() {
        this.updatedList = new ArrayList<>();
        this.timer.schedule(this, 1000);
    }

    @Override
    public void run() {
        System.out.println("使用updatedList进行下游调用");
        this.timer.cancel();
       // downstreamService.update(this.updatedList);
    }

    public void add(String update) {
        this.updatedList.add(update);
    }
}

如果您有任何其他问题,请随时提出。

英文:

I have a requirement to write an implementation where class/object self expires after a specific time. Right now I have extended TimeTask class which invokes run method in a class at a scheduled time and I perform the required downstream service calls. (my sample code below)

I'm not sure of TimerTask is an efficient solution. Can someone please share their thoughts on TimerTask and if there is a better way other than TimerTask?

public class SelfExpiringTask extends TimerTask {

    private List&lt;String&gt; updatedList;
    private Timer timer = new Timer();

    public SelfExpiringTask() {
        this.updatedList = new ArrayList&lt;&gt;();
        this.timer.schedule(this, 1000);
    }

    @Override
    public void run() {
        System.out.println(&quot;Make downstream call with updatedList&quot;);
        this.timer.cancel();
       // downstreamService.update(this.updatedList);
    }

    public void add(String update) {
        this.updatedList.add(update);
    }
}

答案1

得分: 1

Please check javadoc for ScheduledExecutorService

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

英文:

Please check javadoc for ScheduledExecutorService

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

huangapple
  • 本文由 发表于 2020年8月31日 03:42:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63661476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定