Reputation: 2166
I am writing a cron job to my crontab file using following java code
PrintWriter writer = new PrintWriter("/var/spool/cron/crontabs/multi","UTF-8");
String cronTabString="25 13 * * * sudo wget --tries=0 \"https://some-url.com:7443/DataUpdater/updateChildren?folderId="+folderId+"&clientId="+clientId+"&clientSecret="+clientSecret+"&refreshToken="+refreshToken+"&deptName="+deptName+"\"";
writer.println(cronTabString);
writer.close();
The code is successfully writing to cron tab file . But it does not run . My question is that is it even possible to execute a cron job in this manner ? According to me it is a valid cron tab entry , so it should get executed . Am i missing something here ?
Upvotes: 4
Views: 1871
Reputation: 6721
The crontab
scheduler is not just a file. It is a process that runs as a daemon. When you traditionally edit the crontab file its saves the crontab entries and reload the crontab process. Because of this reason, simply writing to the file will not help. You will need to reload or restart the cron daemon.
Update
You can restart the cron daemon if you have root access on the server by using the following command:
/etc/init.d/cron reload
So, in your Java program running on the server, you will need to do this:
Runtime.getRuntime().exec("/etc/init.d/cron reload");
This will run the system command to restart the cron daemon and reload the cron entries.
Hope this helps!
Update 2
Different flavors of Linux have different commands to restart services or daemons.
You can use this as a good starting point to check which command will go as a parameter into the exec
method above.
Cron Command Syntaxes on different Linux Versions
Upvotes: 3
Reputation: 556
Try the following:
crontab -r
crontab /var/spool/cron/crontabs/multi
(edit) I believe in Java, you can call these this way:
Runtime.getRuntime().exec("crontab -r");
Runtime.getRuntime().exec("crontab /var/spool/cron/crontabs/multi");
First one removes the existing crontab. Second one installs the new crontab. And then you can verify by doing:
crontab -l
Upvotes: 3