0

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;
}
kryger
  • 12,906
  • 8
  • 44
  • 65
Nadeem Ahmed
  • 371
  • 2
  • 8
  • 24

3 Answers3

3

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

Amit Bhati
  • 5,569
  • 1
  • 24
  • 45
  • Yes i am using spring .Where will i use @Scheduled(cron="0 0 12 * * ?") ? In my controller or DAO class. – Nadeem Ahmed Jul 29 '15 at 06:35
  • Edited my post. You need to create a Main class, load the spring config file in it. Create a method anywhere where you dao object is injected. create a method, annotate it with @Scheduled and make a call to your Dao method. – Amit Bhati Jul 29 '15 at 06:47
  • i have created a method in my controller. i want to ask if this method will come in my void main() method. Please chk my controller – Nadeem Ahmed Jul 29 '15 at 06:54
  • If you leave the application running in server. Then no need of main() method. Your spring config need to be loaded that's it. Just put the @Scheduled on it. Use this annotation @Scheduled(fixedDelay =30000) for quick debugging. Will fire that method after every 30 seconds. – Amit Bhati Jul 29 '15 at 06:58
  • i created main() method now how to load spring config into it? – Nadeem Ahmed Jul 29 '15 at 07:00
  • public static void main(String[] args) { new ClassPathXmlApplicationContext("your-spring-config.xml"); } – Amit Bhati Jul 29 '15 at 07:01
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/84538/discussion-between-nadeem-ahmed-and-amit-bhati). – Nadeem Ahmed Jul 29 '15 at 07:02
  • Please check my main() method..... @Scheduled(fixedDelay =30000) public static void main(String[] args){ new ClassPathXmlApplicationContext("spring-config.xml"); ProfileDataService profileService = null; try { profileService.getPostList(); } catch (Exception e) { e.printStackTrace(); } – Nadeem Ahmed Jul 29 '15 at 07:09
  • getPostList() is in my DAO class. – Nadeem Ahmed Jul 29 '15 at 07:10
  • No create a method in your dao class or any other bean...then create a method, say, public void scheduleTask(){}..Call profileService.getPostList(); in it. – Amit Bhati Jul 29 '15 at 07:43
  • But how can i set it for specific time.. like 12:00 am at night – Nadeem Ahmed Jul 29 '15 at 08:53
0

You can consider using

  • Cron job which runs on your server and hits the page updating database. You can schedule tasks on the server. Which will be always depended on the machine.
  • You may consider spring schedulers. In this case you will be adding the scheduler part to your application. This will of-course be machine independent. If I was the one to choose, I would be preferring spring scheduler.

Relevant links : Setting up a cron job in Windows

Community
  • 1
  • 1
NewUser
  • 3,729
  • 10
  • 57
  • 79
0

I suggest you to do some readings about Spring Task Execution and Scheduling. It's very well documented. Basically:

  1. Implement Runnable interface in your task (be sure your code is thread safe!)
  2. Obtain ThreadPoolTaskScheduler bean
  3. Schedule your task following like:

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

Gondy
  • 4,925
  • 4
  • 40
  • 46