Friday, February 14, 2014

Automating Jobs in Linux System (Crontab)

We install applications and services in the Ubuntu system and they go on running all the time. So, it is not guaranteed that they run perfectly. Even, some services generate huge log files, or some services go on consuming more and more memory, finally, making the system crash with memory leak. So, to minimize those problems, we implement the auto-restart in the system.

Since, we have different system configuration (such as services, hardware and memory), the way we define auto-restart is different for different system, so we don't make it built-in image characteristics.

The settings of auto-restarting of server is quite easy task if we are familiar with Linux's crontab application.



We can define the automated tasks using crontab command from the terminal as below:
crontab -e
Then we have to select the preferred editor, after that we go into the editor where we define the tasks to run at specified time. We have to add a line for each task in the following format:
minute hour day_of_month month day_of_week command
Note: every users have different crontab file generated in /var/spool/cron/crontabs with the name of the user.
So, that if enough for theory. Now, if we add the following line
20 01 * * 1 sudo reboot
Then it restarts the system every Sunday at 01:20 am.(The user should have super user privilage to restart the system.)
We can change the values according to our requirements.



We can define user wise cron tasks by editing /etc/crontab file. The format is same as above, only we have to provide the user name can execute the defined task, for example:
20 01 * * 1 frietec sudo reboot
So, the user frietec reboots the system every Sunday at 01:20 am.

[Note: the command provided should be executable by the provided user, otherwise, nothing happens.]

If you look into the file /etc/crontab file, you will notice there is already some automated tasks in the folders /etc/cron.hourly /etc/cron.daily /etc/cron.weekly /etc/cron.monthly defined in the file.  So, an alternative will be keep the task(script) in the specified folder to execute at the define time in /etc/crontab file.

clear log files

Log files in linux system are located under /var/log directory. And the long time running system, in case there is some problem, will grow log files size. So, to prevent the system from crashing, we have to implement the mechanism to clear log files.
A simple method to clear log files is to place following line in the crontab job:
0 11 * * 1 find /var/log -type f -delete
This line will find all log files inside /var/log directory and deletes.
The above command can be executed by root user only, so we keep this in root crontab.

No comments:

Post a Comment