How can I release memory after creating matplotlib figures

Solution 1:

Did you try to run you task function several times (in a for) to be sure that not your function is leaking no matter of celery? Make sure that django.settings.DEBUG is set False( The connection object holds all queries in memmory when DEBUG=True).

Solution 2:

import matplotlib.pyplot as plt
from datetime import datetime
import gc

class MyClass:
    def plotmanytimesandsave(self):
        plt.plot([1, 2, 3])
        ro2 = datetime.now()
        f =ro2.second
        name =str(f)+".jpg"
        plt.savefig(name)
        plt.draw()
        plt.clf()
        plt.close("all")


for y in range(1, 10):
    k = MyClass()
    k.plotmanytimesandsave()
    del k
    k = "now our class object is a string"
    print(k)
    del k
    gc.collect

with this program you will save directly as many times you want without the plt.show() command. And the memory consumption will be low.