0

I have a constraint on the server, hence Cron/Autosys is not available for scheduling shell scripts. Is there a way we can schedule a shell script from a java program ? Is quartz scheduler useful ? Can some one provide me a sample code for the same.

Swagatika
  • 3,376
  • 6
  • 30
  • 39

5 Answers5

2

The below tutorial help you to schedule shell script.

http://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

By using

Runtime.getRuntime().exec("sh shellscript.sh");

You can run shell script.

Dhinakar
  • 4,061
  • 6
  • 36
  • 68
1

You can use ProcessBuilder class for executing any process externally from java including batch files. Here Executing another application from Java there is an example.

Instead of timer class, creating a thread checking time with small intervals might solve the time dependency.

public class Test implements Runnable {
    void run () {    
        while(true) {     
            if(myTime != currentTime) {
                // check for the time until your time has come
                // if not, sleep and continue
                sleep(1000);
                continue;
            }

            // Do your job and exit when necessary 
        }
    }
}

you can execute the class with thread.

Community
  • 1
  • 1
serkan
  • 555
  • 7
  • 13
0

This might be of use to you : http://algorithmicallyrandom.blogspot.in/2009/11/tips-and-tricks-scheduling-jobs-without.html

You can use the at command.

Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
0

you can use timer:

int loopTime = 1000*60*60*12;
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
        public void run()
        {
          Runtime.getRuntime().exec("your java command: java -classpath...");
    }
},0, loopTime);   //0 is for delay time in ms, loopTime is also in ms
ItayD
  • 533
  • 6
  • 23
0

Yes, you could use Quartz to schedule your task from Java. Your Job implementation would then invoke Runtime.exec(...) to launch the shell task, and possibly some Process methods to interact with the task. Some tips:

  • As you are going to launch a shell script, rather than directly invoking your shell script with Runtime.exec(...) you should invoke your shell executable and pass your shell script as parameter. That is, instead of exec'ing /path/to/your/shell/script.sh, you should exec sh /path/to/your/shell/script.sh.

  • Quartz scheduler supports cron expressions, see CronTrigger and tutorial on supported cron expressions in Quartz.

  • Obviously, Quartz scheduler jobs will only run as long as you have a JVM running with the Quartz Scheduler service up. Usually you need to take this into account when implementing your jobs.

  • Also, if you do not implement some sort of job persistence, such as JobStoreCMT, you might skip job executions, and dynamically scheduled job executions will not survive a restart.

gpeche
  • 21,974
  • 5
  • 38
  • 51