File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes Writing to a crontab file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Writing to a crontab file" Watch "Writing to a crontab file" New topic

Writing to a crontab file

Mark Kennedy

Joined: Jan 16, 2003
Posts: 3
Hello, all:
I've got a struts app that needs to schedule a task to run at a user specified time. I.e., the user can specify, via a struts JSP page, that they want a given task run at a given time. Based on this input, I want the Action bean to write a line to the crontab file.
My question is, how can I write to the crontab file directly from Java?
I usually edit crontab files from the commandline with crontab -e which then opens the crontab in vi. The crontab file isn't directly editable without using the crontab command, AFAIK. Are there any classes or techniques that can be recommended to do this?
Thanks so much!
Mark Kennedy
Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1141

Hi Mark,
First of all, do you know about the "java.util.Timer" and "java.util.TimerTask" classes (that are part of the JDK since version 1.3)? Are they not suitable?
As a suggestion for implementing your "crontab" solution:
1. "crontab -l" dumps the contents of the "crontab" file. Save the output to some file, example:
crontab -l crontab.fil
2. Edit the file "crontab.fil" using the file manipulating classes from the "" package, or using appropriate UNIX utilities (which you can launch from java using the "java.lang.Runtime" class).
3. Update your "crontab" using the following command:
crontab crontab.fil
Hope this helps.
Good Luck,
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
In the event you need to use crontab and not Timer (e.g. if the JVM may not be running later, but the OS will) you may want to use the Runtime exec() mthod to invoke the commands Avi suggests, from Java.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Writing to a crontab file
jQuery in Action, 3rd edition