aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/Persistence/SqliteShrinkMemoryTimer.cs
blob: b5a0c10b1e4e994c4ea9ff19e0c13b27bbc14fcf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using MediaBrowser.Model.Logging;
using System;
using System.Data;
using System.Threading;

namespace MediaBrowser.Server.Implementations.Persistence
{
    class SqliteShrinkMemoryTimer : IDisposable
    {
        private Timer _shrinkMemoryTimer;

        private readonly SemaphoreSlim _writeLock;
        private readonly ILogger _logger;
        private readonly IDbConnection _connection;

        public SqliteShrinkMemoryTimer(IDbConnection connection, SemaphoreSlim writeLock, ILogger logger)
        {
            _connection = connection;
            _writeLock = writeLock;
            _logger = logger;

            _shrinkMemoryTimer = new Timer(TimerCallback, null, TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(10));
        }

        private async void TimerCallback(object state)
        {
            await _writeLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);

            IDbTransaction transaction = null;

            try
            {
                transaction = _connection.BeginTransaction();

                using (var cmd = _connection.CreateCommand())
                {
                    cmd.Transaction = transaction;
                    cmd.CommandText = "pragma shrink_memory";
                    cmd.ExecuteNonQuery();
                }

                transaction.Commit();
            }
            catch (OperationCanceledException)
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }

                throw;
            }
            catch (Exception e)
            {
                _logger.ErrorException("Failed to save items:", e);

                if (transaction != null)
                {
                    transaction.Rollback();
                }

                throw;
            }
            finally
            {
                if (transaction != null)
                {
                    transaction.Dispose();
                }

                _writeLock.Release();
            }
        }

        public void Dispose()
        {
            if (_shrinkMemoryTimer != null)
            {
                _shrinkMemoryTimer.Dispose();
                _shrinkMemoryTimer = null;
            }
        }
    }
}