The cache 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.
To learn more about cache, click here to visit the LinuxAteMyRAM website. Hopefully, after referring to the website the concept about cache in Linux should get clear.
If you still wish to free up the cache memory then follow the below steps:
Step 1. To clear cache memory in Linux using command:
sync; echo 3 > /proc/sys/vm/drop_caches
In above command 3 means to clear pagecache, dentries & inodes i.e. complete cache.
To clear only page cache
sync; echo 1 > /proc/sys/vm/drop_caches
To clear only inode and dentries
sync; echo 2 > /proc/sys/vm/drop_caches
Step 2. To set cron job to clear cache memory at specific intervals in Linux:
- Access server through shell as a root or sudo user.
- Create a shell script say "clearcache.sh" under root partition and enter following contents
#!/bin/sh sync; echo 3 > /proc/sys/vm/drop_caches
- Now, set the permission of script "/root/clearcache.sh" to 755
chmod 755 /root/clearcache.sh
- Now edit crontab file
- Enter following line to set cron job for clearing cache every hour of first second
0 * * * * /root/clearcache.sh
- Restart cron service
Note: One should be a root user or sudo user to perform the above mentioned operations.
Should I clear cache at regular intervals?
Well it depends upon the situation. On production servers it is not advisable to clear caches at regular since this will force server to serve pages from disk instead of cache thus increasing server load and resources.
If any feedback, queries are always welcome!