33import random
44import threading
55import time
6+ from datetime import datetime , timedelta
7+ from pycron import is_now
68from .template_parser import TemplateParser
79
810
@@ -17,8 +19,20 @@ def __init__(self, engine, template, **kwargs):
1719 threading .Thread .__init__ (self )
1820 self .engine = engine
1921 self .template = str (template )
20- self .prob = kwargs .get ('prob' , 100 )
21- self .freq = kwargs .get ('freq' , (1 , 1 ))
22+
23+ if kwargs .get ('cron_prob' , None ) is not None :
24+ self .cron_prob = kwargs .get ("cron_prob" )
25+ self .set_last_cron_probability ()
26+
27+ self .cron_child = threading .Thread (
28+ target = self .update_cron_probability
29+ )
30+ self .cron_child .setDaemon (True )
31+ self .cron_child .start ()
32+ else :
33+ self .prob = kwargs .get ('prob' , 100 )
34+ self .freq = kwargs .get ('freq' , (1 , 1 ))
35+
2236 self .date_format = kwargs .get ('date_format' , "%Y-%m-%d %H:%M:%S.%f" )
2337 self .interactive = kwargs .get ('interactive' , False )
2438 self .simulation = kwargs .get ('simulation' , False )
@@ -44,6 +58,29 @@ def wait(self):
4458 secs = random .uniform (self .freq [0 ], self .freq [1 ])
4559 time .sleep (secs )
4660
61+ def set_last_cron_probability (self ):
62+ now = datetime .now ()
63+ try :
64+ for _ in range (0 , 525600 ):
65+ for item in self .cron_prob :
66+ if is_now (item ["cron" ], now ):
67+ self .prob = item ['prob' ]
68+ self .freq = item ['freq' ]
69+ raise Exception ('found' )
70+ now = now - timedelta (minutes = 1 )
71+ except Exception as inst :
72+ if inst .args [0 ] != "found" :
73+ raise Exception (inst )
74+
75+ def update_cron_probability (self ):
76+ while True :
77+ for item in self .cron_prob :
78+ if is_now (item ["cron" ]):
79+ self .prob = item ['prob' ]
80+ self .freq = item ['freq' ]
81+ break
82+ time .sleep (60 )
83+
4784 def probability (self ):
4885 """Calculate probability"""
4986 k = random .randint (0 , 100 )
0 commit comments