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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144 | #Author: Orcun Avsar < orc.avs@gmail.com >
import os
import sys
import time
import datetime
import imp
DIR=os.path.abspath(__file__)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
sys.path.append(os.path.split(os.path.split(DIR)[0])[0])
sys.path.append(imp.find_module("django")[1])
class ComponentError(Exception):
def __init__(self,component,components):
self.components=components
self.component=component
def __str__(self):
return "Invalid component:"+self.component+". Available components: "+",".join(self.components)
class BaseCron:
def __init__(self):
self.events={}
self.components=["year","month","day","hour","minute","second"]
def add_event(self,event,period,component,round=False):
if not self.components.count(component):
raise ComponentError(component,self.components)
self.events[event]={"period":period,"component":component,"round":round}
self.find_next(event)
def find_next(self,event):
now=datetime.datetime.now()
comps={"year":now.year,
"month":now.month,
"day":now.day,
"hour":now.hour,
"minute":now.minute,
"second":now.second}
component=self.events[event]["component"]
period=self.events[event]["period"]
if component=="year":
comps[component]+=period
elif component=="month":
comps[component]=range(1, 13)[(comps[component]+period)%12]
if comps[component]==1:comps["year"]+=1
else:
karg={component+"s":period}
time_delta=datetime.timedelta(**karg)
next=now+time_delta
comps={"year":next.year,
"month":next.month,
"day":next.day,
"hour":next.hour,
"minute":next.minute,
"second":next.second}
round=self.events[event]["round"]
extra_time_delta=None
if round:
for comp in self.components[(self.components.index(component))+1:]:
value=1
comps[comp]=value
if component=="year":
comps[component]+=1
elif component=="month":
comps[component]=(range(1, 13)[(comps[component]+1)%12])
if comps[component]==1:comps["year"]+=1
else:
karg={component+"s":1}
extra_time_delta=datetime.timedelta(**karg)
next_visit=datetime.datetime(**comps)
if extra_time_delta:
next_visit+=extra_time_delta
self.events[event]["next_visit"]=next_visit
def start(self):
while 1:
###sorting job###
list=[(self.events[x]["next_visit"],x) for x in self.events.keys()]
list.sort()
event_name=list[0][1]
event_date=list[0][0]
now=datetime.datetime.now()
timedelta=event_date-now
seconds=(timedelta.days*24*60*60)+timedelta.seconds
print "\nnext job: '"+event_name +"' in "+str(seconds)+" seconds..."
if timedelta.days>=0:
time.sleep(seconds)
print "processing job..."
getattr(self,event_name)()
print "finished succesfully."
self.find_next(event_name)
"""
you can import your models here like:
from my_project.entry.models import Entry
start your Cron class here. inherit from BaseCron above
class MyCron(BaseCron):
def __init__(self):
BaseCron.__init__(self)
self.add_event("test_job",3,"minute",True)
def test_job(self):
Entry.objects.all()
create only one instance otherwise only one will work
as cron runs in continuous loop
cron=MyCron()
and start it...
cron.start()
that's all you have to do .
####DETAILS#####
we added a test_job function which is going to run in every three minutes and
will be rounded minutely
add_event function adds a new job to schedule.
-first argument is function name
-second is period length
-third is period component ("second","minute","hour","day","month" or "year"
-last one tells if time should be rounded to period component
e.g. you want to add a job that will run on every day at 24.00 . your add_event function shuld be like that:
self.add_event("midnight_function",1,"day",True)
"""
|
Comments
this works perfect. tnxs!! ;)
#