-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcron.py
68 lines (62 loc) · 2.41 KB
/
cron.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
66
67
68
# CirruxCache provides dynamic HTTP caching on AppEngine (CDN like)
# Copyright (C) 2009 Samuel Alba <[email protected]>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
import logging
import datetime
import web
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.ext.db import stats
import lib.cache
class Cron(object):
def GET(self, request):
if not 'HTTP_X_APPENGINE_CRON' in web.ctx.environ:
return ''
request = request.lower()
if not hasattr(self, request):
return ''
attr = getattr(self, request)
if callable(attr):
attr()
return ''
def expired(self):
"""clear old cache entries"""
# Allow an offset of 1 hour to flush cache entries.
now = datetime.datetime.utcnow() - datetime.timedelta(hours=1)
# entity selection is limited by 1000 but often timeout
limit = 800
batch = []
# Browse all Datastore kinds to find expired entities
for kind in stats.KindStat.all():
if kind.kind_name.startswith('__'):
continue
cache = type(str(kind.kind_name), (lib.cache.Cache,), {})
for obj in cache.all(keys_only=True) \
.filter('expires <=', now) \
.order('expires').fetch(limit):
batch.append(obj)
n = len(batch)
if n == 0:
logging.info('cron: no expired entities.')
return
# batch deletion is limited by 500 but it timeouts above ~200
step = 200
if step > n:
step = n
for i in range(0, limit, step):
db.delete(batch[i:i+step])
logging.info('cron: %s expired entities flushed.' % n)