Tuesday, October 18, 2016

Flushing File every n minutes in Unix / Linux

Hey Friends,

We all know that best way to handle important log files is to set log file rotation policy, but if accidentally any log file is generating & no rotation policy is set. Then this file may hamper disk-space, which may result in fail-over of applications within the mount-point.
So we have a good provision to schedule cronjob based on time interval to flush any such files.

First let us focus on command required to flush data in file:
Let us assume file is under /tmp mountpoint with name as: heavy.log

Command to Flush -
> /tmp/heavy.log

This will clear data in file. Now let us schedule this command job every 5 mins.

Prerequisite: There must be crontab enabled for owner to schedule the job.

How to edit & update cronjob:
Command -

crontab -e

[This will open cron in edit mode] Now you need to type command in time duration format like below:

* * * * * echo '' > /tmp/heavy.log

This will clear / flush file data every minute, but our requirement is to flush it every n mins. So we modify above command as:
*/n * * * * echo '' > /tmp/heavy.log

Where n is any positive integer value with range (0<n<60)

Now what 5 stars indicate in cron file?
Answer - Below is sequence of every star:
* – Every minute
* – Every hour
* – Every day
* – Every month
* – Every day of the week

So */n will make job schedule every n mins & flush data in file.

Once above job is created, you may exit the edit mode of cron by command as:

:wq!

To verify your cron file post changes: You may type:
crontab -l

[Note - Options to work in crontab are same as vi editor]

No comments:

Post a Comment