1

My problem is that I have a RESTful Web Service using a class Gestion. In this class, I have a function _update_, and I would like to call this function everyday at 00:00.

I had no idea how to do that, so I looked into the Web, and I found that using threads might be a good option. However, I don't know how I can use it. Do I have to move my _update_ function into a new class ?

2 Answers2

1

If you are using EJB you can use the timer service

@Singleton
public class TimerService {
    @Inject
    HelloService helloService;

    @Schedule(second="0", minute="0", hour="0")
    public void update(){
        System.out.println("timer: " + helloService.sayHello());
    }
}

https://docs.oracle.com/javaee/7/tutorial/ejb-basicexamples004.htm

kwisatz
  • 1,266
  • 3
  • 16
  • 36
1

Use any open source job or schedulers more details are here. http://toppersworld.com/top-10-open-source-java-job-schedulers/ Or do pure coding. This link may help you. Get milliseconds until midnight. Sleep until midnight in a thread and wake up do task and go and sleep again.

@Override
public void run() {
    while (true) {
        try {
            Thread.sleep(calculateSleepingTime());
            // do what ever you want
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

private long calculateSleepingTime() throws ParseException {

    Calendar c = Calendar.getInstance();
    c.add(Calendar.DAY_OF_MONTH, 1);
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    return (c.getTimeInMillis()-System.currentTimeMillis());
}
Community
  • 1
  • 1
bobs_007
  • 178
  • 1
  • 10