The cache / buffer memory in Linux is nothing but a set of cache stored on the server which contains frequently visited pages. The cache configuration is done in a such a way that whenever any data is requested by RAM it will check the cache memory and serve the data from cache memory if available. This helps to increase the response time and optimum usage of the server resources.
The cache / buffer memory from RAM on Linux and Unix servers can be flushed in different ways.
How to clear cache / buffer memory on a Linux server?
To clear pagecache, dentries & inodes i.e. flush all from cache memory
sync; echo 3 > /proc/sys/vm/drop_caches
To clear only inodes and dentries from cache memory
sync; echo 2 > /proc/sys/vm/drop_caches
To clear only page cache from cache memory
sync; echo 1 > /proc/sys/vm/drop_caches
How to set a cron job to clear cache memory in Linux?
The cache memory may be required to cleaned up at regular intervals and free up the disk space. The same can be achieved by creating a cronjob to automatically clear the cache memory using crontab.
- Access the desired server through shell as a root or sudo user.
- Create a shell script say "clearcache.sh" under root (/root) partition with following commands
#!/bin/sh sync; echo 3 > /proc/sys/vm/drop_caches
- Set the permission of "clearcache.sh" script to 755
chmod 755 /root/clearcache.sh
- Edit the system crontab file using below command
- Enter the following line in crontab file to set cron job for clearing cache memory automatically
0 * * * * /root/clearcache.sh
The above cron job will execute the "clearcache.sh" script every hour of first second.
- Restart cron service
Note: One should be a root user or sudo user to perform the above mentioned operations.
Should I clear / flush cache memory from RAM at regular intervals?
Well it depends upon the situation. On production servers it is not advisable to clear cache at regular since this will force server to serve pages from disk instead of cache till cache is not getting build up thus increasing server load and resources.
To learn more about cache, visit the LinuxAteMyRAM website. Hopefully, after referring to the website the concept about cache in Linux should get clear.
Please let us your feedback, queries by posting in comment section.