Thursday, February 9, 2017

Cron Job Study

To see what crontabs are currently running on your system, you can open a terminal and run:

$ sudo crontab -l

To edit the list of cronjobs you can run:

$ sudo crontab -e

Storing the crontab output
==========================
By default cron saves the output of /bin/execute/this/script.sh in the user's mailbox (root in this case). But it's prettier if the output is saved in a separate logfile. Here's how:

*/10 * * * * /bin/execute/this/script.sh >> /var/log/script_output.log 2>&1

Explained
==========
Linux can report on different levels. There's standard output (STDOUT) and standard errors (STDERR). STDOUT is marked 1, STDERR is marked 2. So the following statement tells Linux to store STDERR in STDOUT as well, creating one datastream for messages & errors:

2>&1

Now that we have 1 output stream, we can pour it into a file. Where > will overwrite the file, >> will append to the file. In this case we'd like to to append:

>> /var/log/script_output.log

Mailing the crontab output
==========================
By default cron saves the output in the user's mailbox (root in this case) on the local system. But you can also configure crontab to forward all output to a real email address by starting your crontab with the following line:

MAILTO="yourname@yourdomain.com"

Mailing the crontab output of just one cronjob
==============================================
If you'd rather receive only one cronjob's output in your mail, make sure this package is installed:

$ aptitude install mailx

And change the cronjob like this:

*/10 * * * * /bin/execute/this/script.sh 2>&1 | mail -s "Cronjob ouput" yourname@yourdomain.com

Trashing the crontab output
============================
Now that's easy:

*/10 * * * * /bin/execute/this/script.sh > /dev/null 2>&1

Just pipe all the output to the null device, also known as the black hole. On Unix-like operating systems, /dev/null is a special file that discards all data written to it.

Resource Link: http://kvz.io/blog/2007/07/29/schedule-tasks-on-linux-using-crontab/

Cron Job Generator Tool: http://www.crontab-generator.org/


  1. http://www.corntab.com/popular_crontabs
  2. https://github.com/lathonez/dotfiles/blob/master/crontab/example.crontab
  3. http://www.dba-oracle.com/linux/scheduling_with_crontab.htm
  4. https://www.debian-tutorials.com/crontab-tutorial-cron-howto
  5. http://stackoverflow.com/questions/18945669/linux-how-to-run-script-at-certain-time

No comments:

Post a Comment