简体   繁体   中英

Selfexpiring object in java (Timertask)

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM