使用Spring在x天后运行一次任务

时间:2017-02-06 00:40:21

标签: java spring

我正在开发一个您拥有OffersCounter-offers的应用程序。当我创建要约时,我想安排一个任务在5天后运行,以检查它是否有任何还价。如果它没有任何还价,则要约状态将设置为已过期。

我已经阅读了@Scheduled注释,但它每x天只运行一个任务,但我想只在创建商品后才运行任务,每个新商品只运行一次。我怎样才能做到这一点?感谢

2 个答案:

答案 0 :(得分:1)

嗨,我迟到了,不是春天的专家,但我有一个解决方案,这个创建一个使用注释的预定组件更容易

class OfferClass {
    public Date creationDate;
    // .... user related info
}

@EnableScheduling
@Component
public class OfferManager {
    private static final long interval_milliSeconds = 60*60*1000; // scheduled to run once every hour
    public List<OfferClass> offersList = new ArrayList<>();

    @Scheduled(fixedRate = interval_milliSeconds)
    public void timeout() {
        Date now = new Date(); // current timestamp
        for (OfferClass offer:this.offersList) {
            // check if 5 days are spent
            if (now.getTime() - offer.date.getTime() > 5 days) {
               // Do your action and remove the offer from the offersList
               this.offersList.remove(offer)
            }
        }
    }

}

// Usage
void main() {
    // Add an offer to the array
    offerClass newOffer = new offerClass();
    newOffer.creationDate = new Date() // set start date
    // Add offer to offer manager and wait for magic
    OfferManager.offersList.add(newOffer)
}

我知道这不是最好的答案并且已经过优化,但我是一个iOS开发人员而不是春天的快速改进将是挖掘“@Scheduled(fixedRate = ...)”注释可能使用其他选项,如cron或fixeDelay可以更好地工作祝你好运

答案 1 :(得分:0)

我没有给你直接答案,而是你可以使用Spring Task Scheduler。

Spring 3.0引入了一个用于调度任务的TaskScheduler。它是Spring-Core的一部分,无需声明额外的依赖。

创建类似于Spring配置的cron作业

<task:scheduled-tasks>
   <task:scheduled ref="offerScheduler" method="processOffer" cron="0 1 * * * *" />
</task:scheduled-tasks>

确保您拥有名为“OfferSchedueled”的课程,并且它具有“processOffer”方法来执行您的逻辑,以便每天凌晨1点更改优惠状态。

@Component
public class OfferSchedueled {

 public void processOffer(){
   //Get all non expired offers into a list or any collection
   //Loop through each of them
  //Check it's time span between created date and today is 5 days
  //if so and it doesn't have any counter offers, then mark that as expired
 }

}

更多阅读:

http://techie-mixture.blogspot.com/2016/07/spring-batch-job-executing-scheduled.html http://howtodoinjava.com/spring/spring-core/4-ways-to-schedule-tasks-in-spring-3-scheduled-example/ https://www.mkyong.com/spring-batch/spring-batch-and-spring-taskscheduler-example/