0

I have a Java web application hosted on a Tomcat server. This web application serves http requests. Now, I need to execute a Java program that interacts with the database and perform some tasks nightly. This Java program needs to run on its own thread and should not cause Tomcat to crash/terminate for any reason (obviously will have try-catch blocks, but still).

And yeah, I don't want to run a cron job in the background. I want the web application to execute the program at a certain time right after deployment.

How can I do this?

i_raqz
  • 2,789
  • 10
  • 48
  • 86
  • Do you have a specific reason to avoid cron jobs? – das-g Oct 02 '15 at 20:58
  • Well, I think Tomcat should be able to handle this. As there could be something that covers the application life cycle just like how we have a servlet life cycle. – i_raqz Oct 02 '15 at 23:46

1 Answers1

1

Look at java Executor Service which can schedule runnable to run periodically at prescribed times:

private ScheduledExecutorService executorService;

@PostConstruct
public void init() {
    executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(this::periodicJob, 1000, 1, TimeUnit.DAYS);
}

private void periodicJob() {
    //load from db, and process
}

Of course you can manipulate the delay and the period.

However, if you can end up in a JavaEE environment (tomee, wildfly, glasfish and the like), you could use the EJB schedule specs:

@Schedule(hour="*/24", persistence=false, info="My scheduled task")
public void doSomethingAwesomeEveryMidnight(){
}
das-g
  • 8,581
  • 3
  • 33
  • 72
maress
  • 3,355
  • 1
  • 16
  • 34