diff --git a/lib/tasks/attachment_maintaining_service.rake b/lib/tasks/attachment_maintaining_service.rake
index 6c95f7716e65dfb676bed42f6dadc37077b70911..701366d5d810b390b79ec0c41f21cf3b29162446 100644
--- a/lib/tasks/attachment_maintaining_service.rake
+++ b/lib/tasks/attachment_maintaining_service.rake
@@ -3,20 +3,28 @@ require 'fileutils'
   namespace :attachment_maintaining_service do
 
     desc 'Removing attachments'
-    task remove_attachments: :environment do
-      sort_directories.first(10).each do |dir|
-        FileUtils.rm_r(dir)
+    task remove_attachments: :environment do |t, args|
+      args.with_defaults(limit: 10.gigabytes)
+      path = attachments_path + "/*"
+      if attachments_size(attachments_path) > args.limit
+        sort_attachments(path).first(10).each do |dir|
+          FileUtils.rm_r(dir)
+        end
       end
     end
 
     private
 
-    def sort_directories
-      Dir[dir_path].sort_by{ |f| File.atime(f) }
+    def attachments_size(dir)
+      `du -s #{dir} | cut -f 1`.to_i
     end
 
-    def dir_path
-      Rails.root.join('public','attachments','*').to_s
+    def sort_attachments(attachments_path)
+      Dir[attachments_path].sort_by{ |f| File.atime(f) }
+    end
+
+    def attachments_path
+      Rails.root.join('public','attachments').to_s
     end
 
   end