Ubuntu – Is it a bad idea to create a cron script that empties the swap every hour


For years I have been having the same problem with my small Ubuntu configurations: the used swap space increases with time. I get the impression that this is mainly because the allocated memory never returns to RAM even though there is enough space for it, except in the case of a user action like disabling the swap.

I made a short cron command to automate this, and I have good results:

#! /bin/sh

echo "* */1 * * * root swapoff -a && swapon -a" >> /etc/crontab

But because it's more of a trick than a real solution to this problem, I'm wondering about the potential reasons it might be a bad idea, or how could I improve this script to make it a little more clever?

Best Answer

  • Using it like that: yes, bad. You really need to check if there is enough memory available before you turn swap off. See https://askubuntu.com/a/90399/15811 for a better version.

    Also: are you sure about this? Swap being allocated does not mean swap being used. The command vmstat, columns si (swap in) and so (swap out). If those remain 0 you got another problem. In my experience swap is hardly used, and you might not be using it thinking it does not empty it but there is nothing to empty.