英文:
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<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("Make downstream call with updatedList");
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论