简体   繁体   中英

Scheduled Annotation in Spring (call after a certain time for each value)

I am working at the moment with @Scheduled Annotation in Spring. What i want to do is, to remove a value from a list after 10 minutes, so the value can only least 10 minutes after creation. Is there a way to implement this with @Scheduled Annotation?

Example:

public int values(){
 for(int i = 0; i < 10;++i){
 Random ran = new Random();
 int x = ran.nextInt(6) + 5;
 list.add(x);
 }
}
@Scheduled(fixedRate = 600000)
public void removeValue(){
 list.remove(list.size()-1);
}

In this example the value gets deleted after 10 minutes. Then i have to wait 10 minutes to delete the next value, but what if the last values are created straight after the deleted value. In summary, i want to call removeValue() after a value in list is 10 minutes old.

It may not be a very good example with a simple List object element, but you can do what you want to do using your own model or the Map interface.

First of all, you can simply add your elements to a Map interface and delete them in a minimum of 10 minutes by keeping an expired time for each element. The example in the link can be a reference for the map interface. How to Remove expired elements from HashMap and Add more elements at the Same Time – Java Timer, TimerTask and futures() – Complete Example

If you have a database entity; you can call these expired elements and delete them from the database. As an example, I had a code block like this.

To sum up, I take elements whose creation date is older than 10 minutes. All that remains is to delete this.

Date retentionDate = org.apache.commons.lang3.time.DateUtils.addMinutes(new Date(), -10);
List<?> items = service.findAllByCreationDateBefore(retentionDate);

Remember to set the fixedRate value accordingly for how long you want Elaman to stay for more than 10 minutes.

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