Repository navigation
Expand file tree
/
Copy pathTimer.py
More file actions
96 lines (70 loc) · 2.71 KB
/
Copy pathTimer.py
File metadata and controls
96 lines (70 loc) · 2.71 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env python
# -*- mode: python; indent-tabs-mode: nil; -*- coding: utf-8 -*-
"""
Timer.py
Copyright 2010-2013 by Marcello Perathoner
Distributable under the GNU General Public License Version 3 or newer.
A cron-like process that runs at fixed intervals.
Usage:
import Timer
cherrypy.process.plugins.Timer = TimerPlugin
"""
from __future__ import unicode_literals
import datetime
import logging
import psycopg2
import cherrypy
from libgutenberg import GutenbergDatabase
import BaseSearcher
class TimerPlugin (cherrypy.process.plugins.Monitor):
""" Plugin to start the timer thread.
We cannot start any threads before daemonizing,
so we must start the timer thread by this plugin.
"""
def __init__ (self, bus):
frequency = 300
super (TimerPlugin, self).__init__ (bus, self.tick, frequency)
self.name = 'timer'
self._last_refresh_date = None
def start (self):
super (TimerPlugin, self).start ()
self.tick ()
start.priority = 80
def tick (self):
""" Do things here. """
try:
BaseSearcher.books_in_archive = BaseSearcher.sql_get ('select count (*) from books')
except:
pass
refresh_hour = cherrypy.config.get ('mv_refresh_hour', 17)
now = datetime.datetime.now ()
if now.hour == refresh_hour and self._last_refresh_date != now.date ():
self._try_refresh_mv ()
def _try_refresh_mv (self):
""" Refresh mv_books_dc, skipping if another instance is already refreshing.
— Zachary Rosario
Bypasses the pool to avoid statement timeout errors.
pguser needs EXECUTE on refresh_mv_books_dc() and ownership of mv_books_dc.
"""
conn = None
try:
params = GutenbergDatabase.get_connection_params (cherrypy.config)
conn = psycopg2.connect (**params)
cur = conn.cursor ()
# Transaction-level advisory lock keyed on the view's OID.
# Auto-releases on commit/rollback no explicit unlock needed.
cur.execute ("""
SELECT pg_try_advisory_xact_lock(c.oid::bigint)
FROM pg_class c WHERE c.relname = 'mv_books_dc'
""")
if not cur.fetchone ()[0]:
return
cur.execute ("SELECT refresh_mv_books_dc()")
conn.commit ()
self._last_refresh_date = datetime.datetime.now ().date ()
cherrypy.log ("MV refresh completed.", context='TIMER', severity=logging.INFO)
except Exception as e:
cherrypy.log ("MV refresh failed: %s" % e, context='TIMER', severity=logging.ERROR)
finally:
if conn:
conn.close ()