4

I want to be able to setup linux cron jobs from a java program.

I know to setup a cron job, i use the crontab tool:

crontab -e

and then specify the cron expressions.

How do i do this programmatically from a java program?

Thanks

maress
  • 3,533
  • 1
  • 19
  • 37

2 Answers2

1

You can (assuming you have permission) directly modify your crontab file using Java's many file I/O functions. The file can (at least on my system) be found at:

/var/spool/cron/crontabs/paxdiablo

(for the user paxdiablo). Simply make whatever changes you want to this file and then send a HUP signal to the cron daemon.

However, directly editing that file is frowned upon and indeed it may well be protected from you.

To do it properly, you can use the crontab -l command to capture the current contents to a file (eg, me.cron). The crontab -l command writes your crontab file to standard output, unlike crontab -e which tries to bring it up in an editor.

Then you can use whatever means you wnt to modify that file (it's yours because you created it).

Then, running crontab me.cron will install that file (with any changes you've made) and notify cron so that it re-reads it.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

You could do it like this:

String cmd = "crontab -e";
ProcessBuilder builder = new ProcessBuilder("bash", "/c" , cmd);
builder.redirectErrorStream(true);
Process p = builder.start();
Michael Brenndoerfer
  • 3,483
  • 2
  • 39
  • 50
  • Why redirect error stream? If i could write to the outputstream of the process, and then write to it? – maress Nov 13 '13 at 07:55