简体   繁体   English

Spring 中的计划注释(每个值在一定时间后调用)

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

I am working at the moment with @Scheduled Annotation in Spring.我目前正在 Spring 中使用@Scheduled Annotation。 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.我想要做的是,在 10 分钟后从列表中删除一个值,因此该值只能在创建后至少 10 分钟。 Is there a way to implement this with @Scheduled Annotation?有没有办法用@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.在此示例中,该值在 10 分钟后被删除。 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.然后我必须等待 10 分钟才能删除下一个值,但如果最后一个值是在删除值之后直接创建的呢? In summary, i want to call removeValue() after a value in list is 10 minutes old.总之,我想在列表中的值 10 分钟后调用 removeValue() 。

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.使用简单的List object 元素可能不是一个很好的示例,但是您可以使用自己的 model 或Map接口来做您想做的事情。

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.首先,您可以简单地将元素添加到Map接口,并通过为每个元素保留expired time在至少 10 分钟内删除它们。 The example in the link can be a reference for the map interface.链接中的示例可以作为 map 接口的参考。 How to Remove expired elements from HashMap and Add more elements at the Same Time – Java Timer, TimerTask and futures() – Complete Example 如何从 HashMap 中删除过期元素并同时添加更多元素 – Java Timer、TimerTask 和 futures() – 完整示例

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.综上所述,我选取了创建日期超过 10 分钟的元素。 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.请记住根据您希望 Elaman 停留超过 10 分钟的时间相应地设置fixedRate值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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