How to Create Linux-Cron Job  from a Java Program

Hello,
Can anybody help me to CREATE/EDIT/DELETE Linux Cron job from Java Program. Its Very Urgent.Thanks in advance..
from
Chakri

I decided this didn't sound too tough so I played around with it a little. Basically because I'd never tried executing external processes out of java before, so I wanted to see how it was done.
Just change whatever you like in the jobs ArrayList and call writeJobs.
If you call writeJobs without putting anything in the list first you'll wipe out all of your crontab entries.
import java.lang.*;
import java.io.*;
import java.util.*;
public class cron {
    ArrayList jobs;
    Runtime rt;
    cron() {
     rt = Runtime.getRuntime();
     jobs = new ArrayList();
    void readCron() {
     String[] list = { "crontab", "-l" };
     jobs = new ArrayList();
     try {
         // Stick a job into crontab
         Process child = rt.exec(list);
         BufferedReader cronout = new BufferedReader(new InputStreamReader(child.getInputStream()));
         String cronjob = cronout.readLine();
         while (cronjob != null) {
          jobs.add(cronjob);
          cronjob = cronout.readLine();
         child.waitFor();
     catch(IOException e) {
         System.err.println("IOException starting process!");
     catch(InterruptedException e) {
         System.err.println("Interrupted waiting for process!");
    void listJobs() {
     Iterator iter = jobs.iterator();
     while (iter.hasNext()) {
         System.out.println((String)iter.next());
    void writeJobs() {
     String[] edit = { "crontab"};
     try {
         // Stick a job into crontab
         Process child = rt.exec(edit);
         PrintWriter cronIn = new PrintWriter(child.getOutputStream());
         Iterator iter = jobs.iterator();
         while (iter.hasNext()) {
          cronIn.println((String)iter.next());
         cronIn.close();
         child.waitFor();
     catch(IOException e) {
         System.err.println("IOException starting process!");
     catch(InterruptedException e) {
         System.err.println("Interrupted waiting for process!");
    void doStuff() {
     readCron();
     listJobs();
     jobs.add("* * * * 4 cronjob");
     writeJobs();
     readCron();
     listJobs();
    public static void main(String[] args) {
     cron c = new cron();
     c.doStuff();
}

Similar Messages

  • How to run a openssl command from a java program

    Hi All
    Please suggest on how to run a openssl command from a java program.
    I am using this
    Runtime runtime = Runtime.getRuntime();
    runtime.exec("openssl pkcs8 -inform der -nocrypt test.der result.pem");
    This is suppose to take test.der as input and create result.pem.
    There are no errors but the file result.pem isnt created.
    Thanks in Advance

    First off is that openssl command correct? Should it be this instead:
    openssl pkcs8 -inform der -nocrypt -in test.der -out result.pem
    Try out your openssl command within a command prompt so that you know that it works ok. I think the command line you specified waits on stdin (well it does for me).
    After that.....
    runtime.exec creates a Process object. If you do this:
    Process openssl = runtime.exec("....")
    then you can examine the return code from openssl to see the exit code - for instance if the input file does not exist then exit = 1. You can test for this with Java
    Alternatively you could get the stderr from the process and look inside it - if it is 0 length then all is good, if it has some text in there then it has likely failed. You could then throw an exception and include the stderr output in the exception messgae. You may need to experiment with this, runnig it first when openssl is happy then running it again when openssl is upset.
    M

  • How to display a oracle table from a java program?

    How to display a oracle table from a java program.
    Hello friends, I have written a Java program, using oracle 10g as backend.
    I want to display a oracle table as output. Im not getting how to display oracle table as a output table.. Pls help me
    Thank you

    jayanthds, you're not going to get a satisfactory
    answer to this here. it's too big a task to justbe
    quickly outlined in a forum - the reply "all youneed
    to do is to query you table and return it asJTable"
    is worthless, for example, since the solution to
    any problem can be distilled to such a
    soundbite, if need be. doesn't make the solutionany
    simpler
    essentially you're asking "how do I write adatabase
    application?". all you'll get is snippets of code
    that, when fitted together, will eventually helpyou
    do this, but you'll spend days and days comingback
    saying "right, I've done that, now what?" until
    either you or the forum gets frustrated with the
    whole affair and the process stops
    there are entire books written about this subject,
    and countless tutorials and guides on theinternet.
    you're better off going down that routehehehe.well, it's true! I used to have a manager that would outline the solution to a problem in a few lines of pseudocode, and then firmly believe that the actual solution would be just as brief and simple. shame his pseudocode included such lofty abstractions as "reformat all data"

  • How to call j2me emulator instance from a java program?

    hi,
    how to call j2me emulator instance from a java program?
    i tried public void startApp(){
    try{
    platformRequest("tel:+5550000");
    }catch(Exception e){
    e.printStackTrace();
    from a j2me midlet itself,
    but it gave illegal access exception.
    do i need any hardware phone connected to my pc?
    please help.

    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    import java.util.*;
    public class OpenExplorer{
    public static void main(String args[]){
         new OpenExplorer();
    public OpenExplorer(){
         try{
         String command = "explorer C:";
         // or String command = "cmd /c explorer C:";
         Runtime runtime = Runtime.getRuntime();
         Process process = runtime.exec(command);
         int exitVal = process.waitFor();
         System.out.println("Exit Value: " + exitVal);
         } catch(Exception e){
         e.printStackTrace();
    }

  • Running a Linux command "clear" from a Java program

    Hello. How to run a simple linux command to clear the screen from a Java program. I did the following
    Process p = Runtime.getRuntime().exec("clear");
    Nothing is happening.

    you're not supposed to mess with the shell, youdon't own it and
    shouldn't try to dictate what happens with it.
    The shell is a multiuser system,What?
    The command shell (for example sh, ksh, bash, csh,
    zsh) is a process, a command interpeter just like any
    other (user mode) program.
    yes, and there can be multiple processes writing to it at any one time.
    You do NOT have exclusive access to it, nor should you ever assume you do.
    In a multiuser system there can be several shells
    running on behalf of several users. The same user can
    run several shells.
    Yes, and each shell can be accessed by multiple processes at any one time.
    So what?
    Process a writes to the shell.
    Process b writes to the shell.
    Process a clears the shell, removing whatever process b wrote there.
    You've just messed up process b, or at the very least its output.
    Do NOT assume you have exclusive access to any shell.

  • How to list all OS processes from a java program

    I want to list/kill all OS processes from a java program, or a part from all processes according to a filter on a name of process.
    a similar functionality is ps in Unix or taskkill in Windows XP.
    Thanks!

    Hi,
    I was looking for such lib, but finally I decided to accomplish the job with my fingers end ;-). It maigh be helful for u guys:
    // is written for x based OSs
    private static void killProcess(Process process) {
    if (process == null)
    return;
    process.destroy();
    private static void closeProcessStreams(Process process) {
    try {
    process.getErrorStream().close();
    } catch (IOException eyeOhEx) {
    private static void listPHPs() {
    Process proc = null;
    Runtime rt = Runtime.getRuntime();
    int exitVal = 0;
    try {     
    proc = rt.exec(" ps -C php"); // here use ur filter. issue "man ps" in linux for more info
    catch (Exception ex) {
    System.out.println(ex.getMessage());
    killProcess(proc);
    return;
    try {
    // process the return list of ur command
    InputStream stdReturnStr = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdReturnStr);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    String returnMsg = "";
    boolean firstLine = true;
    int[] allPIDs = new int[100]; // finally we have an array of PIDs
    int PIDCount = 0;
    while ( (line = br.readLine()) != null) {
    if (!firstLine){ // the first line is title, ignore it
    returnMsg += line + "\n";
    String PID = line.trim().split(" ")[0];
    System.out.println(PID);
    try{
    allPIDs[PIDCount] = Integer.parseInt(PID);
    PIDCount++;
    }catch(Exception ex){           
    else
    firstLine = false;
    System.out.println(returnMsg);
    catch (Exception t) {
    System.out.println(t.getMessage());
    killProcess(proc);
    return;
    try {
    exitVal = proc.waitFor();
    catch (Exception t) {
    System.out.println(t.getMessage());
    killProcess(proc);
    return;
    closeProcessStreams(proc);
    Thats it!

  • How to create a directory or Folder  using java program?

    Hi all,
    Can any one know, how to create a directory(new folder) in java.
    can any give me some idea, on creating a directory using java program dynamically.
    thanx in advance

    hi thanks for your answer,
    sorry, actual i know this technique(its my fault i didnt mentioned it)
    i am looking for some what different technique.
    bye
    ram

  • How to run a cygwin.bat from a java program?

    Can you please let me know how to run a cygwin.bat file from a java program and to give commands through java program. I have a program to run .exe files, but when I do the same for the cygwin.bat it doesnt work. In task mgr a BASH and a cmd.exe is running. Please help me on this & bit urgent. Thanks in advance!

    Can you please let me know how to run a cygwin.bat
    file from a java program and to give commands through
    java program. I have a program to run .exe files, but
    when I do the same for the cygwin.bat it doesnt work.Of course not. .bat files are no native executables. You need to open a shell first, like "cmd /c cygwin.bat ..."
    & bit urgent. Thanks in advance!If I had read this earlier I wouldn't have replied. Why exactly is your time worth more than anybody else's?

  • How can I pass system commands from a java program? Urgent!

    hi,
    I have been trying this out since a long time. How do I send system commands to command.com or cmd.exe from a java program and an output of the executed command back to the java application.
    If u have any idea, or have any information about the kind os application reply back.
    Thanks
    Deepa Datar

    This is the code which I tried, but it displays only the title of MS-DOS, something like " Microsoft Corp...etc ". But doesn't take any input, and the subprocess(cmd.exe) hangs.
    import java.io.*;
    public class cmddemo2
    public static void main(String arg[])
    try
    System.out.println("cmd");
    Process p=Runtime.getRuntime().exec("cmd.exe");
    DataInputStream din=new DataInputStream(p.getInputStream());
    DataOutputStream dout=new DataOutputStream(p.getOutputStream());
    System.out.println("after streams");
    String s;
    dout.writeChars("type cmddemo2.java");
    while((s=din.readLine())!="\n")
    System.out.println(s);
    dout.writeChars("dir");
    String s1;
    while((s1=din.readLine())!="\n")
    System.out.println(s1);
    System.out.println("over");
    catch(Exception e)
    { System.out.println("Exception : "+e);

  • How to read files on server from a java program?

    Hello,
    I am fairly new to JSP programming. I have an issue with reading files. I am trying to call method of a normal java file from a jsp program. The method I am trying to call does some IO operation on Files. I have the files in the same directory as my class files on server that is in WEB-INF/classes folder. In my java program, I am giving just the file name to open because the files and the classes are in the same directory. But this is not working.
    What exactly should I do to read a file from a java program, that is running on the server?
    Any help is appreciated.
    Thanks,
    Krishna

    String realFilePath = application.getRealPath("/WEB-INF/myFile.txt");
    File fileToOpen = new File(realFilePath);
    out.println(fileToOpen.getAbsolutePath() + ": exists? " + fileToOpen.exists());in this case "application" is a reference to the ServletContext.
    It is an implicit variable in a JSP. In a servlet:
    ServletContext application = getServletConfig().getServletContext();

  • How to open my computer window from a java program.....

    To open my computer window in win xp is simple from the start menu.
    i want to open it from a java program .
    any idea to open my computer from a java program or command prompt......

    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    import java.util.*;
    public class OpenExplorer{
    public static void main(String args[]){
         new OpenExplorer();
    public OpenExplorer(){
         try{
         String command = "explorer C:";
         // or String command = "cmd /c explorer C:";
         Runtime runtime = Runtime.getRuntime();
         Process process = runtime.exec(command);
         int exitVal = process.waitFor();
         System.out.println("Exit Value: " + exitVal);
         } catch(Exception e){
         e.printStackTrace();
    }

  • How to create multiple WIP jobs from a single Sales Order Line

    Hi all,
    I want to know if there's a standard way to create multiple single unit wip jobs from a sales order line which has 2 or more units, i mean...
    I have a sales order line with item A with 3 units. If I progress the sales order, a single job is automatically created in WIP with 3 units to be created. What i want is to create 3 jobs with one unit each, all of them linked to the sales line order...
    Thanks in advance!
    Regards!

    Assuming simplest of scenarios....
    In case of changes to Sales order qty, an unplanned order will simply disappear.
    If a wip job has already been created, you will get a cancel message (in case the job is not needed) or a reschedule out message (if the quantity needs to be reduced).
    ASCP will give you a reschedule in /out message if the dates change.
    Sandeep Gandhi

  • How to create windows executable file from a java file. Please help.

    Hi,
    For my project I developed the codes in Java. It is working well with java run time environment. But without that I can not run it. I need to create a exe file (windows executable file) from the java source code. If you have any idea please share it with me.
    Even if you know it very lightly, please help with what you know. That would be a big help for me.
    Thank you very much.

    Does anybody know how to read a manual?
    Matt Richardson
    Certified LabVIEW Developer
    MSR Consulting, LLC

  • How to submit a HTTP Request from a Java Program

    I am working on an web based application where in I need to submit the HttpRequest through a Java Program and not through browser. Moreover my intent is just to submit the HttpRequest. I donot want to wait for the response to come back. I have used the URL Connection class to do the same and I am trying to post this request. The contents of the methods that I am using are as below:-
    public void doPost(URL url, String inputXMLString) throws IOException
              //Create URLConnection based on the passed URL
              URLConnection connection = url.openConnection();
              connection.setDoOutput(true);
              connection.setDoInput(false);
              connection.setUseCaches(false);
              connection.setAllowUserInteraction(false);
              connection.setRequestProperty("Content-type", "application/x-www-form-
    urlencoded");
              //Get the Connection's output stream and write the request to it.
              PrintWriter out = new PrintWriter(connection.getOutputStream());
              out.print("&ena-request-input=" + URLEncoder.encode(inputXMLString));
              out.flush();
              out.close();
    Call to the above method does not invoke the URL I am intending to submit the request at.
    Can anybody give me the clue....................................................?

    I agree with the advice to launch a new thread to read and ignore the response. I don't think you should have to do it to make it work, but it's worth trying for two reasons:
    1) If it turns out it does make it work, well, then either you can leave it that way, or use that as a clue to help figure out how to make it work the way you want.
    2) There may be an error message there that will give you an idea why it's not working.
    When you say it's not invoking the servlet, what does that mean, and how do you know? Is it just that the final results aren't being seen? Put a bunch of logging statements in the servlet. It could be that it's getting hit, but you're corrupting the string you're building, or sending some extra junk that it can't handle. Spit out a log statement from the start of doPost, to see if it's even getting there. Then log the parameter. Enclose the output in quotes or braces or something to make sure there's not extra junk. I've had XML docs not parse because there was a blank line at the beginning.
    If it works in the browser but not from your standalone app, then you need to have the servlet tell what difference it sees in the two cases. Print out headers, other params, everything you can think of.
    Re-read the docs for URL, HttpURL, whatever, to make sure you're doing all the right steps in the right order. Make a servlet that just takes a single, simple param=value via POST and see if you can get that to work.

  • How can I get the events from a java program?

    I want to make a monitor to watch a java program.How can I get the events from the GUI of this program some as mouse cliking, keyinput. So I can watch these in my monitor.
    Thanks

    Hi,
    To put a monitor to the events occuring in the GHUI u need to register required components with the appropriate EventListeners.
    Liek if u want to get notified when a mouse is clicked, then u need to add The MouseListener to the component which u want to be monitored.
    Say
    myFrame which is the JFrame object which shuld be monitored for the events.
    Then in ur program u have to add following code
    myFrame.addMouseListener( someObectReference );
    Here the someObjectReference should be an instance to a concrete class ..i.e. U write a class like the following
    public class MyMouseListener implements MouseListener {
    // override the followig methods
    public void mouseClicked(MouseEvent me){ sop("MOUSE CLICKED ON THE FRAME");}
    public void mousePressed(MouseEvent me){}
    public void mouseReleased(MouseEvent me){}
    If u dont want to use another class for listening to the events. Then u can make teh current class monitor the events. To do so ur class should implement the appropriate listener and should override the required methods.
    and u should say myFrame.addMouseListenet( this );
    thats it

Maybe you are looking for

  • How do you convert NTSC footage to PAL?

    I've got some footage on a Mini-DV tape recorded with an NTSC camera, which I need to edit in my FCE PAL project. I can playback and see the footage on my Sony DSR-PDX10 DVCam, but FC Express doesn't recognise it when I connect my camera to my comput

  • P745: Possible Bad Hard Drive. How do I get Toshiba Recovery Wizard on New HD?

    Hey everyone last week my computer was behaving slouchy so I did a simple restart. When it restarted it took me to a screen which said loading "Windows files" then it took me to Startup Repair. Startup repair could not repair the issue and I did a fe

  • Using array in forall

    I was wondering what the syntax is for using a forall with a array. I want to do something like below but this doesnt work correctly. forall i in 1 .. p_array.COUNT insert into test_object (attr_id, attr_1, attr_2) values (p_array(i).attr_id, p_array

  • CAN ANYONE TELL ME BY THIS .... WHAT'S HAPPENING????

    Process:         iMovie [7147] Path:            /Applications/iMovie.app/Contents/MacOS/iMovie Identifier:      com.apple.iMovieApp Version:         9.0.9 (1795) Build Info:      iMovieApp-1795000000000000~2 App Item ID:     408981434 App External ID

  • Archiving stops with no reason

    Hi, I'm trying to enable archiving on a XE database: 1. Change from 2 redo log groups to 3 adding one and change the size to 100M each file. 2. Enable archiving. Shutdown Mount alter database archivelog Open Shutdown Startup Until this point all went