Skip to content

Commit 93aa3b2

Browse files
committed
upd: data is automatically collected into the database every 5 minutes
1 parent ba11cc5 commit 93aa3b2

File tree

8 files changed

+86
-27
lines changed

8 files changed

+86
-27
lines changed
325 Bytes
Binary file not shown.

app/core/bot.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,24 @@
33
from aiogram import Bot, Dispatcher
44

55
from app.handlers.basic import register_basic_handlers
6+
from app.services.metrics import wait_for_clock
67

78
async def main():
89
bot = Bot(token=os.getenv("BOT_TOKEN"))
910
dp = Dispatcher()
1011

1112
register_basic_handlers(dp)
1213

13-
await dp.start_polling(bot)
14+
metrics_task = asyncio.create_task(wait_for_clock())
15+
16+
try:
17+
await dp.start_polling(bot)
18+
finally:
19+
metrics_task.cancel()
20+
try:
21+
await metrics_task
22+
except asyncio.CancelledError:
23+
pass
1424

1525
if __name__ == "__main__":
1626
asyncio.run(main())

app/database/database.py

Lines changed: 45 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,48 @@
11
import sqlite3
22
import time
3+
from pathlib import Path
4+
import asyncio
5+
from concurrent.futures import ThreadPoolExecutor
6+
7+
DB_PATH = Path(__file__).resolve().parent / 'server_metrics.db'
8+
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
9+
10+
# Thread pool for async database operations
11+
_executor = ThreadPoolExecutor(max_workers=1)
12+
13+
def _save_to_db_sync(data):
14+
with sqlite3.connect(DB_PATH) as connection:
15+
cursor = connection.cursor()
16+
17+
create_query = '''
18+
CREATE TABLE IF NOT EXISTS Metrics (
19+
id INTEGER PRIMARY KEY AUTOINCREMENT,
20+
timestamp INTEGER NOT NULL,
21+
mem_total REAL,
22+
mem_used REAL,
23+
mem_prcnt REAL,
24+
cpu_prcnt REAL,
25+
cpu_freq REAL,
26+
cpu_temp REAL
27+
);
28+
'''
29+
cursor.execute(create_query)
30+
31+
ts = int(time.time())
32+
33+
insert_query = '''
34+
INSERT INTO Metrics (timestamp, mem_total, mem_used, mem_prcnt, cpu_prcnt, cpu_freq, cpu_temp)
35+
VALUES (?, ?, ?, ?, ?, ?, ?);
36+
'''
37+
params = (ts, data['mem_total'], data['mem_used'], data['mem_prcnt'],
38+
data['cpu_prcnt'], data['cpu_freq'], data['cpu_temp'])
39+
cursor.execute(insert_query, params)
40+
connection.commit()
41+
42+
print("Success")
43+
44+
async def save_to_db(data):
45+
"""Async wrapper for database operations to avoid blocking the event loop"""
46+
loop = asyncio.get_event_loop()
47+
await loop.run_in_executor(_executor, _save_to_db_sync, data)
348

4-
with sqlite3.connect('server_metrics.db') as connection:
5-
cursor = connection.cursor()
6-
7-
create_query = '''
8-
CREATE TABLE IF NOT EXISTS Metrics (
9-
timestamp INTEGER PRIMARY KEY,
10-
cpu REAL,
11-
ram REAL,
12-
temp REAL
13-
);
14-
'''
15-
cursor.execute(create_query)
16-
17-
ts = int(time.time())
18-
metrics = (ts, '23.5', '45.7', '43.2')
19-
20-
insert_query = '''
21-
INSERT INTO Metrics (timestamp, cpu, ram, temp)
22-
VALUES (?, ?, ?, ?);
23-
'''
24-
cursor.execute(insert_query, metrics)
25-
connection.commit()
26-
27-
print("Success")
0 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.
946 Bytes
Binary file not shown.

app/services/clock.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import asyncio
2+
3+
class Clock:
4+
clock_event = asyncio.Event()
5+
6+
async def five_min_clock(self):
7+
while True:
8+
self.clock_event.set()
9+
await asyncio.sleep(0)
10+
self.clock_event.clear()
11+
await asyncio.sleep(300)

app/services/metrics.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import asyncio
2+
from app.services.clock import Clock
3+
from app.database.database import save_to_db
14
import psutil
25
p = psutil
36

@@ -23,7 +26,7 @@ async def get_resources(self):
2326
self.cpu_temp = round(sum([c.current for c in cores]) / len(cores), 1)
2427
break
2528

26-
async def pack_resources(self):
29+
def pack_resources(self):
2730
resources = {
2831
'mem_total': self.mem_total,
2932
'mem_used': self.mem_used,
@@ -33,4 +36,18 @@ async def pack_resources(self):
3336
'cpu_temp': self.cpu_temp
3437
}
3538

36-
return resources
39+
return resources
40+
41+
async def wait_for_clock():
42+
clock = Clock()
43+
asyncio.create_task(clock.five_min_clock())
44+
45+
res = Resources()
46+
47+
while True:
48+
await Clock.clock_event.wait()
49+
Clock.clock_event.clear() # Clear the event after processing
50+
await res.get_resources()
51+
data = res.pack_resources()
52+
await save_to_db(data)
53+
print("saved")

0 commit comments

Comments
 (0)