如何在一天内安排一次Hibernate程序

时间:2015-07-29 06:17:49

标签: java spring hibernate

我正在使用带有Hibernate的Spring REST,我开发了一个程序,其中数据来自数据库计算,并且它被更新到数据库中的另一个表中。但是我想在一天中的某一天运行这个程序,因为我想在一天中只计算一次结果。我怎么能这样做?

这是我的 DAO

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

这是我的控制器

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

3 个答案:

答案 0 :(得分:3)

http://quartz-scheduler.org/
  你需要一个调度程序。您可以配置每天安排的方法,如下面春季所述:

1)在spring config中:

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

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

2)启用注释:

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

3)使用您想要安排的@Scheduled注释注释方法

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

上面的cron表达式将每天中午12点(中午)安排该方法 某些通用cron表达式的链接:http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger

答案 1 :(得分:0)

您可以考虑使用

  • 在您的服务器上运行并访问页面更新数据库的Cron作业。您可以在服务器上安排任务。这将始终取决于机器。
  • 您可以考虑spring schedulers.在这种情况下,您将把调度程序部分添加到您的应用程序中。这当然是机器独立的。如果我是选择的人,我会更喜欢弹簧调度程序。

相关链接: Setting up a cron job in Windows

答案 2 :(得分:0)

我建议你做一些关于Spring Task Execution and Scheduling的阅读。它有很好的记录。 基本上是:

  1. 在您的任务中实现Runnable接口(确保您的代码是线程安全的!)
  2. 获取ThreadPoolTaskScheduler bean
  3. 按照以下方式安排您的任务:

    scheduler.schedule(task,new CronTrigger(“* 15 9-17 * * MON-FRI”));

相关问题