-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtasks.py
65 lines (52 loc) · 1.67 KB
/
tasks.py
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
"""This module contains all scheduled tasks that is necessary for the app."""
import api
import config
import os
import logging
from logging.config import dictConfig
from apscheduler.schedulers.blocking import BlockingScheduler
from models import XRate, ApiLog, ErrorLog
# Initialize a scheduler
sched = BlockingScheduler()
dictConfig(config.LOGGING)
log = logging.getLogger("Tasks")
@sched.scheduled_job('interval', hours=1)
def update_rates():
"""The function for periodic updating all rates in the application."""
log.info("Job started")
xrates = XRate.select()
for rate in xrates:
try:
api.update_rate(rate.from_currency, rate.to_currency)
except Exception as ex:
log.exception(ex)
log.info("Job finished")
@sched.scheduled_job('interval', days=7)
def cleanup():
"""The function for periodic erasing all logs."""
# Erase internal app's logs
log.info("Cleanup started")
try:
if os.path.exists("app.log"):
os.remove("app.log")
log.info("Logs cleaned")
else:
log.exception("Logs file does not exist")
except Exception as ex:
log.exception(ex)
# Erase logs of calls to external APIs and occurred errors
try:
for table_log in ApiLog, ErrorLog:
table_log.drop_table()
table_log.create_table()
log.info(f"{table_log.__name__} cleaned")
except Exception as ex:
log.exception(ex)
log.info("Cleanup finished")
def start():
"""Scheduler entrypoint"""
sched.start()
log.info("Scheduler started")
# Start as a module (necessary for manual start)
if __name__ == '__main__':
start()