0

I wrote a core Java program that will update the database based on some criteria. It just fetched some data from table and manipulates it and store the new data.

I need to run this program at 3.0 am everyday.

can a core java program be run in a web server through cron jobs.

Or only servlet can be run on the server side? I'm new to this. Please help.

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225
user2186465
  • 197
  • 1
  • 1
  • 14
  • You need simply to call `YourApp.main(new String[] {});` If you do not use System.exit or leak resources. Maybe an easy port might be due, replacing System.out.println with logging. – Joop Eggen Sep 29 '14 at 10:39
  • Google for **Quartz Scheduler** Servlet Example. You will get your answer. Use – Swaraj Sep 29 '14 at 10:56

3 Answers3

1
crontab 0 3 * * * myshell.sh

where your shell runs java -jar myapp.jar

or simply use build-in db sheduler

Dmitry
  • 330
  • 1
  • 14
0

some details are missing but:

  1. if you use a web server (tomcat?) only to use a container for the application, you can consider to deploy the application as a standalone jar, and then execute it using linux crontab (assuming you're using linux). usage example 1, usage example 2. i don't know if you need it, but when you execute the task with crontab, you can pass arguments to the executed task.

  2. if you decided to use the web server, then you can write a java code, that schedules a timed task (you can schedule it with a specific time to run, an interval). when the task is executed, it can then run the code that manipulates the data. there are different implementation for the issue (java's TimerTask, quartz and more). you can read about them here.

Community
  • 1
  • 1
javaist
  • 43
  • 7
0

As mentioned by Drimity you can put the java program run command in a script and schedule the script.

echo "start"
java YourClass
echo "end"

Its a good practice to redirect all output of your java program to a log file instead of System.out /System.err

However, there is a much better way if you're using Java EE and on a Java EE server. Server will schedule the job for you. All you need is an annotation.

import javax.ejb.Schedule;
import javax.ejb.Singleton;


@Singleton
public class ShedulerEjb {


    /**
     * This scheduler method runs at 0200 hours (system time)
     */
    @SuppressWarnings("unused")
    @Schedule(hour="2", minute="0", second="0")
    private void doStuff(){
        //Do your stuff
    }   
   }

Underneath it uses operating system's timer services.

PS: If you don't make your bean singleton and at the scheduled time, there are more than one instances (say n) of your EJB bean, the scheduled method will be executed n number of times.

Community
  • 1
  • 1
ares
  • 4,283
  • 6
  • 32
  • 63