How to plan a Hibernate program once a day

advertisements

I am using Spring REST with Hibernate and I have developed a program in which data is coming from database calculate and it is updated into another table in database. But I want to run this program once in a day at a given time because I want to calculate result only one time in a day. How can I do this?

Here is my DAO class

@SuppressWarnings({ "unchecked", "rawtypes" })
  public List<Result> getPostList() throws Exception {
      session = sessionFactory.openSession();
      tx = session.beginTransaction();

      Criteria cr = session.createCriteria(Post.class);
      ProjectionList projList = Projections.projectionList();
      projList.add(Projections.sum("val"), "topValue");
      projList.add(Projections.groupProperty("userId"), "uid");
      cr.addOrder(Order.desc("topValue"));
      cr.setProjection(projList);
      cr.setResultTransformer(Transformers.aliasToBean(Result.class));
      List<Result> postList = cr.list();
      // please make sure that you are using the class field name rather than database field name in below query.
      String updateHql = "update Result set topValue = :topValue where id = :uid";
      Query query = null;
      int count = 1;
      for(Result result : postList){
        query=session.createQuery(updateHql);
       // query.setLong("topValue", result.getTopValue());
        query.setLong("topValue", count);
        query.setLong("uid", result.getUid());
        count++;
        query.executeUpdate();
        session.flush();
      }

      session.flush();
      tx.commit();
      return postList;
  }

Here is my Controller

@RequestMapping(value = "/posts", method = RequestMethod.GET)
public @ResponseBody
List<Result> getEmployee() {

    List<Result> postList = null;
    try {
        postList = profileService.getPostList();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return postList;
}


http://quartz-scheduler.org/
You need a scheduler for it. You can configure a method to be scheduled everyday as explained below in spring:

1) In spring config:

<task:scheduler id="scheduler" pool-size="10" />
<task:executor id="executor" pool-size="10" />

<task:annotation-driven scheduler="scheduler" executor="executor" />

2) Enable annotation:

<context:component-scan annotation-config="true" base-package="" />

3) Annotate the method with @Scheduled annotation which you want to be scheduled

@Scheduled(cron="0 0 12 * * ?")
public void scheduledTask(){
}

Above cron expression will schedule the method at 12pm (noon) every day.
Link for some generic cron expressions: http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger