def send_reminder_mail(sender, **kwargs): s = Scheduler() start_date = kwargs['instance'].start_date.date() s.add_date_job(send_reminder_mail_job, start_date, [kwargs['instance']]) s.start()
class Scheduler(object): """ The Zato's job scheduler. All of the operations assume the data's being first validated and sanitized by relevant Zato public API services. """ def __init__(self, singleton=None, init=False): self.singleton = singleton self.broker_token = None self.zmq_context = None self.client_push_broker_pull = None if init: self._init() def _init(self): self._sched = APScheduler() self._sched.start() def wait_for_init(self): """ Sleeps till the background APScheduler's thread is up and running. """ self._init() while not self._sched.running: time.sleep(0.01) def _parse_cron(self, def_): minute, hour, day_of_month, month, day_of_week = [elem.strip() for elem in def_.split()] return minute, hour, day_of_month, month, day_of_week def _on_job_execution(self, name, service, extra, broker_msg_type): """ Invoked by the underlying APScheduler when a job is executed. Sends the actual execution request to the broker so it can be picked up by one of the parallel server's broker clients. """ msg = {'action': SCHEDULER.JOB_EXECUTED, 'name':name, 'service': service, 'payload':extra, 'cid':new_cid()} self.singleton.broker_client.send(msg) if logger.isEnabledFor(logging.DEBUG): msg = 'Sent a job execution request, name [{0}], service [{1}], extra [{2}]'.format( name, service, extra) logger.debug(msg) def create_edit(self, action, job_data, broker_msg_type=MESSAGE_TYPE.TO_PARALLEL_ANY): """ Invokes a handler appropriate for the given action and job_data.job_type. """ if logger.isEnabledFor(logging.DEBUG): logger.debug(job_data) if not job_data.is_active: msg = 'Job [{0}] is not active, not scheduling it'.format(job_data.name) logger.info(msg) return handler = '{0}_{1}'.format(action, job_data.job_type) handler = getattr(self, handler) try: handler(job_data, broker_msg_type) except Exception, e: msg = 'Caught exception [{0}]'.format(format_exc(e)) logger.error(msg)
def run_cron_cleanup(settings): ''' Read cron scheduling entries and schedule ''' cron_time = {} year = settings.get("extract.cleanup.schedule.cron.year") month = settings.get("extract.cleanup.schedule.cron.month") day = settings.get("extract.cleanup.schedule.cron.day") week = settings.get("extract.cleanup.schedule.cron.week") day_of_week = settings.get("extract.cleanup.schedule.cron.day_of_week") hour = settings.get("extract.cleanup.schedule.cron.hour") minute = settings.get("extract.cleanup.schedule.cron.minute") second = settings.get("extract.cleanup.schedule.cron.second") if year is not None: cron_time['year'] = year if month is not None: cron_time['month'] = month if day is not None: cron_time['day'] = day if week is not None: cron_time['week'] = week if day_of_week is not None: cron_time['day_of_week'] = day_of_week if hour is not None: cron_time['hour'] = hour if minute is not None: cron_time['minute'] = minute if second is not None: cron_time['second'] = second if len(cron_time) > 0: sched = Scheduler() sched.start() sched.add_cron_job(delete_stats, **cron_time)
def handle(self, *args, **options): sched = Scheduler() sched.start() from twilio.rest import TwilioRestClient account_sid = "AC6fe90756ae4096c5bf790984038a3f32" auth_token = "97e8833ee3553bc4d9d16e86f1865d32" client = TwilioRestClient(account_sid, auth_token) for user in user_list: user_schedule = Schedule.objects.all().filter(user=user) for schedule in user_schedule: day_of_week = schedule.day_of_week hour = schedule.hour minute = schedule.minute user_message = schedule.message print 'BEFORE:' + str(user_message) def timed_job(msg): print 'AFTER' + str(msg) sched.add_cron_job(lambda: timed_job(user_message), second='0-60') #sched.start() print 'test' while True: pass
def update_celery_tasks_status(): schedudler = Scheduler(daemonic = False) @schedudler.cron_schedule(second='*/30', max_instances=1) def update_job(): infos = RedisHelper.get_all_celery_tasks_info() res_ids = get_tasks_uuid('start_spider') for res_id in infos: is_complete = False info = infos[res_id] spider_name = RedisStrHelper.split(info)[1] if res_id in res_ids: res = app.AsyncResult(res_id) if res.state == 'SUCCESS': is_complete = True else: if res.state == 'FAILURE': print res.trackback() ## TODO: warning pass RedisHelper.update_celery_task_status(res_id, res.state) else: is_complete = True if is_complete: if spider_name in source_home_spiders: # time.sleep(1 * 60) call(spider_name) RedisHelper.del_celery_task_status(res_id) schedudler.start()
def startScheduler(): schedule = Scheduler() schedule.add_interval_job(doCleanUp, days=1) schedule.start() print 'Scheduler has started.' while True: time.sleep(5)
class SnortScheduler(SimplePlugin): """ Enables Schduling for Snortmanager """ scheduler = None # The APS instance def __init__(self, bus): """ Initiates scheduler. """ SimplePlugin.__init__(self, bus) self.scheduler = Scheduler() def __initiate_jobs(self): """ Adds schedueled tasks if database is empty. """ sched = self.scheduler sched.add_cron_job(update_snort_rules, hour = 7, jobstore='sql') sched.add_cron_job(produce_configuration_files, hour = 9, jobstore='sql') def start(self): """ Intitates scheduler when Snortmanager starts """ sched = self.scheduler sched.add_jobstore(ScheduleStore(), 'sql') if len(sched.get_jobs()) is 0: self.__initiate_jobs() sched.start() def stop(self): """ Stops Scheduler service when thread dies. """ self.scheduler.shutdown(wait=False) def restart(self): """ Restarts the service if necassary. """ self.stop() self.start() def get_jobs(self): return self.scheduler.get_jobs()
def add_items(request): seller = request.user if seller: if request.method == "POST": item_name = request.POST['name'] #find way to pass null to image_url item = { "item_name" : item_name, "seller" : seller, "status" : "Available", "date_added" : datetime.now(), "min_bid" : request.POST['min_bid'] } res = add_doc(index= 'item', type=Item, id = item_name, doc= item) from apscheduler.scheduler import Scheduler sched = Scheduler() sched.start() exec_time= datetime.now() + timedelta(seconds=5) job1 = sched.add_date_job(sell_items, exec_time, [item_name]) return HttpResponse("Added Item: {}".format(item_name), status= 200) else: return HttpResponse("Please log in") #redirect to login
def callback(): # Start the scheduler sched = Scheduler() sched.start() alarmMonth = userentermonth.get() print len(alarmMonth) #DEBUG print alarmMonth #DEBUG alarmDay = userenterday.get() print len(alarmDay) #DEBUG print alarmDay #DEBUG alarmYear = userenteryear.get() print len(alarmYear) #DEBUG print alarmYear #DEBUG alarmHour = userenterhour.get() print len(alarmHour) #DEBUG print alarmHour #DEBUG alarmMinute = userenterminute.get() print len(alarmMinute) #DEBUG print alarmMinute #DEBUG # alarmMonth = 5 # alarmDay = 1 # alarmHour = 5 # alarmMinute = 30 # add values in here to set lighting variables so that they remain static # Schedules job_function for specific date and time sched.add_cron_job(AlarmOn, year=alarmYear, month=alarmMonth, day=alarmDay, hour=alarmHour, minute=alarmMinute) lbl.configure(text="Alarm Set!")
class IsItWar(Plugin): def __init__(self, skype): super(IsItWar, self).__init__(skype) self.falseMessages =["The world is still safe, Russia has not declared war yet", "http://suptg.thisisnotatrueending.com/archive/29138254/images/1388285593271.jpg", "http://www.meh.ro/original/2010_03/meh.ro3771.jpg", "http://d24w6bsrhbeh9d.cloudfront.net/photo/arpBmWp_700b_v1.jpg", "http://d24w6bsrhbeh9d.cloudfront.net/photo/aXb2VAv_700b.jpg", "http://d24w6bsrhbeh9d.cloudfront.net/photo/aLKXd6v_700b.jpg"] self.sched = Scheduler() self.sched.start() self.sched.add_interval_job(self.is_it_war, minutes=10) self.command = "isitwaryet" def message_received(self, args, status, msg): res = urllib.urlopen("http://www.bbc.co.uk/news") text = res.read() if "declares war" in text.lower(): msg.Chat.SendMessage("Brace your selves, mother Russia is coming") else: msg.Chat.SendMessage(choice(self.falseMessages)) def is_it_war(self): print "checking if war" res = urllib.urlopen("http://www.bbc.co.uk") text = res.read() if "declares war" in text.lower(): chat = self.skype.Chat("#stigrk85/$jvlomax;b43a0c90a2592b9b") chat.SendMessage("Brace yourself, Mother Russia is coming") def help(self, msg): msg.Chat.SendMessage("usage: @isitwaryet\nWill tell you if Russia has declared war")
def start_scheduler(event): sched = Scheduler() sched.start() sched.add_interval_job(manage_queue, kwargs={'settings': event.app.registry.settings}, seconds=2)
def app(global_config, **settings): """ This function returns a WSGI application. It is usually called by the PasteDeploy framework during ``paster serve``. """ zcml_file = settings.get('configure_zcml', 'configure.zcml') db_string = settings.get('db_string') if db_string is None: raise ValueError("No 'db_string' value in application configuration.") initialize_sql(db_string) config = Configurator(root_factory=get_root, settings=settings) config.begin() config.load_zcml(zcml_file) config.end() # Ugly hack to configure the MapperExtension with the settings. removal_extension.path = settings.get('upload_directory') scheduler = Scheduler() # Send out queued mails from eportfolio.utilities.mail_delivery import trigger_queued_delivery scheduler.add_interval_job(trigger_queued_delivery, seconds=30) scheduler.start() return config.make_wsgi_app()
def schedule(gmclient, opts): sched = Scheduler() sched.daemonic = False @sched.cron_schedule(hour="2-23", minute=00) def movie_task(): task = MovieTask(opts) gmclient.submit_job(task) @sched.cron_schedule(hour="2-23", minute=10) def series_task(): task = SeriesTask(opts) gmclient.submit_job(task) @sched.cron_schedule(hour="2-23", minute=30) def useries_task(): task = UpdatingSeriesTask(opts) gmclient.submit_job(task) @sched.cron_schedule(hour="2-23", minute=00) def error_episode_task(): task = DownloadErrorEpisodeTask(opts) gmclient.submit_job(task) sched.start()
def __init__(self): logging.basicConfig(filename=str(app.config['CONFIG']['logfile']),level=logging.INFO) sched = Scheduler(daemon=True) sched.start() sched.add_interval_job(lambda: self.fetch_report_by_interval(), hours=int(app.config['CONFIG']['scheduler']['hourly_interval'])) while True: pass
class Wikipedia(Plugin): def __init__(self, skype): super(Wikipedia, self).__init__(skype) self.daily_channels = ["#stigrk85/$jvlomax;b43a0c90a2592b9b"] self.sched = Scheduler() self.sched.start() self.command = "wikipedia" self.sched.add_cron_job(self.dailyWikipedia, hour=18, minute=0, day_of_week="mon-sun") def message_received(self, args, status, msg): if (len(args) == 1 and args[0] == "random") or not args: url = self.fetch_randWiki() msg.Chat.SendMessage(url) else: try: page = wiki.wikipedia.page(" ".join(args)) if page.url: msg.Chat.SendMessage(urllib.unquote(page.url)) else: msg.Chat.SendMessage("Could not find any results for {}".format(" ".join(args))) except wiki.exceptions.DisambiguationError: msg.Chat.SendMessage("Your search is disambiguous") except wiki.exceptions.PageError: msg.Chat.SendMessage("Could not find any results for {}".format(" ".join(args))) def fetch_randWiki(self): r = requests.get("http://en.wikipedia.org/wiki/Special:Random") return r.url def dailyWikipedia(self): for channel in self.daily_channels: chat = self.skype.Chat(channel) chat.SendMessage("Dagens random wikipedia: " + self.fetch_randWiki())
def schedule(): logging.info("[+]shivascheduler.py: INSIDE SCHEDULER") sched = Scheduler() duration = server.shivaconf.getint('analyzer', 'schedulertime') sched.add_interval_job(resetcounter, minutes=duration) sched.start() logging.info("Shiva scheduler, which dumps data into maindb, resets global counter and sends data on hpfeeds, started at %s and would execute every %d minutes " % (datetime.datetime.now(), duration))
class IntegrationTestBase(object): def setup(self): self.jobstore = self.make_jobstore() self.scheduler = Scheduler() self.scheduler.add_jobstore(self.jobstore, 'persistent') self.scheduler.start() def test_overlapping_runs(self): # Makes sure that "increment" is only ran once, since it will still be # running when the next appointed time hits. vals = [0] self.scheduler.add_interval_job(increment, jobstore='persistent', seconds=1, args=[vals, 2]) sleep(2.5) eq_(vals, [1]) def test_max_instances(self): vals = [0] events = [] self.scheduler.add_listener(events.append, EVENT_JOB_EXECUTED | EVENT_JOB_MISSED) self.scheduler.add_interval_job(increment, jobstore='persistent', seconds=0.3, max_instances=2, max_runs=4, args=[vals, 1]) sleep(2.4) eq_(vals, [2]) eq_(len(events), 4) eq_(events[0].code, EVENT_JOB_MISSED) eq_(events[1].code, EVENT_JOB_MISSED) eq_(events[2].code, EVENT_JOB_EXECUTED) eq_(events[3].code, EVENT_JOB_EXECUTED)
class TrackerManager(object): '''Manages process information collection for multiple processes''' LOG = logging.getLogger('pt.tracker_manager') def __init__(self, interval): TrackerManager.LOG.debug( "Initializing TrackerManager with interval = %s", interval) self.listeners = [] self.probes = [] self.scheduler = Scheduler() self.scheduler.add_interval_job(self.tracking_job, seconds=interval) self.scheduler.start() def add_listener(self, listener): '''Add listener that will receive metrics''' self.listeners.append(listener) def add_probes(self, probes): '''Add probe that will collect metrics''' self.probes.extend(probes) def tracking_job(self): '''a job that monitors''' results = [] for probe in self.probes: results.extend(probe()) self.submit(results) def submit(self, results): '''publish results to listeners''' for listener in self.listeners: listener.submit(results)
class SayulitaMain(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.speaker = Synthetizer("festival", "spanish") self.scheduler = Scheduler() self.scheduler.start() def initialization(self): self.speaker.speechit("Aqui proyecto Sayulita operado por x e uno gol yanqui quebec") self.speaker.speechit("Estacion experimental de texto a voz") def features(self): self.clock = Clock() self.news = FeedParserRss() def logging(self, command): if command == 'start': logging.basicConfig(filename='sayulita.log', filemode='w', level=logging.INFO) logging.basicConfig(format='%(asctime)s %(message)s') logging.info('Started') def scheduling(self): #self.scheduler.interval_schedule(seconds=1) #self.clock.clockget() self.news.getitems self.scheduler.add_cron_job(self.clock.clockget,month='*',day='*',hour='*',minute ='*',second='0') self.scheduler.add_cron_job(self.initialization,month='*',day='*',hour='*',minute ='*',second='15') self.scheduler.add_cron_job(self.news.getitems,month='*',day='*',hour='*',minute ='15,30,45',second='15') self.scheduler.print_jobs()
def watchlist(request): #Handle file upload global location if 'import' in request.POST: form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() location = newdoc.path() # Redirect to the document list after POST return HttpResponseRedirect(reverse('scraper.views.watchlist')) else: form = DocumentForm() # An empty, unbound form if 'match' in request.POST: call_command('readfile', location) sched = Scheduler(standalone = True) def match_sched(): call_command('readfile', location) sched.add_interval_job(match_sched, seconds = 20, max_instances = 1000) sched.start() # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render_to_response( 'scraper/index2.0.html', {'documents': documents, 'form' : form}, context_instance = RequestContext(request) )
class SimpleScheduler: def __init__(self): self._sched = Scheduler() self._sched.start() self._jobs = {} def schedule(self, job): if job.name in self._jobs: logger.warn("Already have job with name: %s" % job.name) return False try: self._sched.add_cron_job(job._execute_and_store, **job.schedule) except TypeError: logger.error("Invalid schedule for job with name: %s" % job.name + " schedule: %s" % job.schedule) self._jobs[job.name] = job return True def schedules(self): return {job.name: job.schedule for job in self._jobs.values()} def execute(self, name): return self._sched.add_date_job(self._jobs[name]._execute_and_store, datetime.now() + timedelta(seconds=1))
def main(): from apscheduler.scheduler import Scheduler if len(sys.argv) != 2: sys.exit("usage: %s <config-file>" % sys.argv[0]) try: from ConfigParser import ConfigParser except ImportError: # python3 from configparser import ConfigParser try: config = ConfigParser(inline_comment_prefixes=(';',)) except TypeError: # not python3 config = ConfigParser() config.readfp(open(sys.argv[1])) global logfile logfile = config.get("global", "logfile") FORMAT = "%(asctime)-15s: %(message)s" logging.basicConfig(level=logging.INFO, filename=logfile, filemode='w', format=FORMAT) # Set time on WDLXTV systems rdate = "/usr/sbin/rdate" if os.path.exists(rdate) and os.access(rdate, os.X_OK): cmd = [rdate, "ntp.internode.on.net"] subprocess.Popen(cmd).wait() logging.info("Main process PID: %d, use this for sending SIGHUP " "for re-reading the schedule-file", os.getpid()) global tuners tuners = TUNERS(config.get("global", "tuners")) global hdhomerun_config hdhomerun_config = config.get("global", "hdhomerun_config") schedule_file = config.get("global", "schedule_file") media_dir = config.get("global", "media_dir") channelmap = {} for opt in config.options("channelmap"): channelmap[opt] = config.get("channelmap", opt).split(",") while True: global reload_jobs, shutdown reload_jobs = False shutdown = False sched = Scheduler(misfire_grace_time=60, daemonic=False) sched.start() signal.signal(signal.SIGHUP, sighup_handler) signal.signal(signal.SIGTERM, sigterm_handler) schedule_jobs(sched, schedule_file, channelmap, media_dir) while not (reload_jobs or shutdown): signal.pause() sched.shutdown() if shutdown: sys.exit(0)
def __init__(self, **kwargs): """ Args: weeks: number of weeks to wait days: number of days to wait hours: number of hours to wait minutes: number of minutes to wait seconds: number of seconds to wait verbose: (int) verbosity level max_njobs_inque: Limit on the number of jobs that can be present in the queue use_dynamic_manager: True if the :class:`TaskManager` must be re-initialized from file before launching the jobs. Default: False max_nlaunches: Maximum number of tasks launched by radpifire (default -1 i.e. no limit) """ # Options passed to the scheduler. self.sched_options = AttrDict( weeks=kwargs.pop("weeks", 0), days=kwargs.pop("days", 0), hours=kwargs.pop("hours", 0), minutes=kwargs.pop("minutes", 0), seconds=kwargs.pop("seconds", 0), #start_date=kwargs.pop("start_date", None), ) if all(not v for v in self.sched_options.values()): raise self.Error("Wrong set of options passed to the scheduler.") self.mailto = kwargs.pop("mailto", None) self.verbose = int(kwargs.pop("verbose", 0)) self.use_dynamic_manager = kwargs.pop("use_dynamic_manager", False) self.max_njobs_inqueue = kwargs.pop("max_njobs_inqueue", 200) self.contact_resource_manager = as_bool(kwargs.pop("contact_resource_manager", False)) self.remindme_s = float(kwargs.pop("remindme_s", 4 * 24 * 3600)) self.max_num_pyexcs = int(kwargs.pop("max_num_pyexcs", 0)) self.max_num_abierrs = int(kwargs.pop("max_num_abierrs", 0)) self.safety_ratio = int(kwargs.pop("safety_ratio", 5)) #self.max_etime_s = kwargs.pop("max_etime_s", ) self.max_nlaunches = kwargs.pop("max_nlaunches", -1) self.debug = kwargs.pop("debug", 0) if kwargs: raise self.Error("Unknown arguments %s" % kwargs) if has_sched_v3: from apscheduler.schedulers.blocking import BlockingScheduler self.sched = BlockingScheduler() else: from apscheduler.scheduler import Scheduler self.sched = Scheduler(standalone=True) self.nlaunch = 0 self.num_reminders = 1 # Used to keep track of the exceptions raised while the scheduler is running self.exceptions = collections.deque(maxlen=self.max_num_pyexcs + 10) # Used to push additional info during the execution. self.history = collections.deque(maxlen=100)
def tasks(hour): """run tasks, keep it running for crawler""" sched = Scheduler(standalone=True) # http://pythonhosted.org/APScheduler/modules/scheduler.html sched.add_cron_job(douban_spider_task, hour=int(hour)) sched.start() info = 'start tasks at' + datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S') spider_task_log.log_info(info)
def run_scheduler(app): scheduler = Scheduler() expire_wrapper = lambda: expire_sessions(app) scheduler.add_interval_job(expire_wrapper, seconds=EXPIRE_SESSION_EVERY) scheduler.start() print "APScheduler started successfully"
def init(self,threadpool = None): if threadpool is None : self.sched = Scheduler({'apscheduler.threadpool.core_threads':1, 'apscheduler.threadpool.max_threads':1, 'apscheduler.threadpool.keepalive':1}) else: self.sched = Scheduler({'apscheduler.threadpool':threadpool}) self.sched.daemonic = False
def create_app(configFile): crowdsourcingWebApp=CrowdsourcingWeb(configFile); apschedulerObj = Scheduler() apschedulerObj.start() #apschedulerObj.add_cron_job(clean_expire_function,year="*", month="*", day="*", hour="*",minute="*",second="*",args=[crowdsourcingWebApp]); return crowdsourcingWebApp;
def daemon(): worker_minutes = cfg.get("job.switch_cfg_persistence", "run_on_minutes") logger.info("Starting persistence-control daemon...") logger.info("The persistence-control worker will run on minutes '%s'..." % worker_minutes) sched = Scheduler() sched.add_cron_job(worker, minute=worker_minutes) sched.start() signal.pause()
class AdvancedPythonScheduler(object): def __init__(self): self.scheduler = Scheduler() self.scheduler.start() def schedule_interval_task(self, action, weeks=0, days=0, hours=0, minutes=0, seconds=0): self.scheduler.add_interval_job(action, weeks, days, hours, minutes, seconds)
def start_scheduled_jobs(): sched = Scheduler() sched.start() # add scheduler jobs below if app.config.get('IS_PRODUCTION'): sched.add_interval_job(sqldump_job, days=1)
bittrexTask(cursor) bitfinexTask(cursor) poloniex(cursor) conn.close() regex = re.compile('trades_.*.db') files = sorted(filter(regex.match, os.listdir('.')), reverse=True) if len(files) > 1 and os.environ.has_key('access_key'): access_key = os.environ['access_key'] secret_key = os.environ['secret_key'] q = Auth(access_key, secret_key) bucket_name = 'stock' for item in files[1:]: token = q.upload_token(bucket_name, item, 60) ret, info = put_file(token, item, item) print info if ret['hash'] == etag(item): os.remove(item) logger.info('leave task') cronTask() if __name__ == '__main__': sched = Scheduler(standalone=True, misfire_grace_time=5) sched.add_interval_job(cronTask, seconds=5, coalesce=True) try: sched.start() except (KeyboardInterrupt, SystemExit): pass
def main(): # Start the scheduler sched = Scheduler() sched.start() sched.add_cron_job(miami.zeroing, hour='23') miami.app.run(host='0.0.0.0', port=5000)
class OutcallAction: def __init__(self, host_id, start_time, duration, program): self.__host_id = host_id self.start_time = start_time self.duration = duration self.program = program self.__scheduler = Scheduler() self.__available_calls = dict() self.__in_talkshow_setup = False self.__host = None self.__community_call_UUIDs = dict() self.__invitee_call_UUIDs = dict() self.__call_handler = self.program.radio_station.call_handler self.__phone_status = PhoneStatus.QUEUING self.__interested_participants = Set([]) self.__collecting_digits_to_call = False self.__invitee_number = "" def start(self): try: self.__in_talkshow_setup = True self.__host = self.__get_host(self.__host_id) if self.__host is None or self.__host.phone is None: self.stop(False) return self.program.set_running_action(self) self.__scheduler.start() self.__call_handler.register_for_incoming_calls(self) self.__call_handler.register_for_incoming_dtmf(self, str(self.__host.phone.raw_number)) self.__call_handler.register_for_host_call(self, str(self.__host.phone.raw_number)) self.request_host_call() except Exception as e: print e def stop(self, graceful=True, call_info=None): self.hangup_call() # Stop scheduler self.__scheduler.shutdown() # deregister from any triggers self.__call_handler.deregister_for_incoming_calls(self) self.__call_handler.deregister_for_incoming_dtmf(str(self.__host.phone.raw_number)) self.program.notify_program_action_stopped(graceful, call_info) def __get_host(self, host_id): host = self.program.radio_station.db.query(Person).filter(Person.id == host_id).first() return host def request_host_call(self): self.__in_talkshow_setup = True result = self.__call_handler.call(self, self.__host.phone.raw_number, None, False, 15) # call ends in 15 mins max self.program.log_program_activity("result of host call is " + str(result)) if not result[0]: self.stop(False) def __request_station_call(self): if self.program.radio_station.station.is_high_bandwidth: result = self.__call_station_via_sip() if result is None or not result[0]: # Now try calling the SIM (ideally do primary, then secondary) result = self.__call_station_via_goip() else: result = self.__call_station_via_goip() if result is None or not result[0]: self.stop(False) def __call_station_via_sip(self): result = None # Try a high bandwidth call first if self.program.radio_station.station.sip_username is not None: result = self.__call_handler.call(self, self.program.radio_station.station.sip_username, self.__host.phone.raw_number, True, self.duration) self.program.log_program_activity("result of station call via SIP is " + str(result)) return result def __call_station_via_goip(self): result = None if self.program.radio_station.station.primary_transmitter_phone is not None: result = self.__call_handler.call(self, self.program.radio_station.station.primary_transmitter_phone.raw_number, self.__host.phone.raw_number, False, self.duration) self.program.log_program_activity("result of station call (primary) via GoIP is " + str(result)) if not result[ 0] and self.program.radio_station.station.secondary_transmitter_phone is not None: # Go for the secondary line of the station, if duo SIM phone result = self.__call_handler.call(self, self.program.radio_station.station.secondary_transmitter_phone.raw_number, self.__host.phone.raw_number, False, self.duration) self.program.log_program_activity("result of station call (secondary) via GoIP is " + str(result)) return result def notify_call_answered(self, answer_info): if self.__host.phone.raw_number not in self.__available_calls: self.__available_calls[answer_info['Caller-Destination-Number'][-12:]] = answer_info self.__inquire_host_readiness() self.program.log_program_activity("host call has been answered") elif 'Caller-Destination-Number' in answer_info and answer_info['Caller-Destination-Number'][-12:] == self.__invitee_number: self.__available_calls[answer_info['Caller-Destination-Number'][-12:]] = answer_info self.__invitee_number = ""; self.__collecting_digits_to_call = False else: # This notification is from station answering call self.__available_calls[answer_info['Caller-Destination-Number'][-12:]] = answer_info self.__call_handler.speak('You are now on air', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) # result1 = self.__schedule_warning() # result2 = self.__schedule_hangup() self.__call_handler.register_for_call_hangup(self, answer_info['Caller-Destination-Number'][-12:]) def warn_number(self): seconds = self.duration - self.__warning_time if self.__host.phone.raw_number in self.__available_calls and 'Channel-Call-UUID' in self.__available_calls[ self.__host.phone.raw_number]: result = self.__call_handler.speak( 'Your call will end in ' + str(seconds) + 'seconds', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) self.program.log_program_activity("result of warning is " + result) def __pause_call(self): # hangup and schedule to call later self.__schedule_host_callback() self.hangup_call() def notify_call_hangup(self, event_json): if 'Caller-Destination-Number' in event_json: if event_json[ 'Caller-Destination-Number'] in self.__community_call_UUIDs: # a community caller is hanging up del self.__community_call_UUIDs[event_json['Caller-Destination-Number']] self.__call_handler.deregister_for_call_hangup(event_json['Caller-Destination-Number']) elif event_json['Caller-Destination-Number'] in self.__invitee_call_UUIDs: del self.__invitee_call_UUIDs[event_json['Caller-Destination-Number']] self.__call_handler.deregister_for_call_hangup(event_json['Caller-Destination-Number']) elif event_json['Caller-Destination-Number'] == self.__host.phone.raw_number or \ event_json['Caller-Destination-Number'] in \ [self.program.radio_station.station.sip_username, self.program.radio_station.station.primary_transmitter_phone.raw_number, self.program.radio_station.station.secondary_transmitter_phone.raw_number]: # It is a hangup by # the station or the host self.program.log_program_activity( "Program terminated because {0} hangup".format(event_json['Caller-Destination-Number'])) self.stop(True) def __inquire_host_readiness(self): if self.__phone_status == PhoneStatus.WAKE: self.__call_handler.speak( 'You have a caller on the line. To connect to the station, press one, to cancel, press two', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) else: self.__call_handler.speak( 'You are scheduled to host a talk show at this time. If you are ready, press one, if not ready, press two', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) self.program.log_program_activity("Asking if host is ready") def hangup_call(self): # hangup the ongoing call for available_call in self.__available_calls: self.__call_handler.deregister_for_call_hangup(available_call) self.__call_handler.hangup(self.__available_calls[available_call]['Channel-Call-UUID']) self.__available_calls = dict() # empty available calls. they all are hung up def notify_incoming_dtmf(self, dtmf_info): dtmf_json = dtmf_info dtmf_digit = dtmf_json["DTMF-Digit"] if dtmf_digit == "*": # enter a number to be called followed by the # key self.__collecting_digits_to_call = not self.__collecting_digits_to_call if not self.__collecting_digits_to_call: self.__invitee_number = "" elif not self.__collecting_digits_to_call: if dtmf_digit == "1" and self.__in_talkshow_setup: self.program.log_program_activity("Host is ready, we are calling the station") self.__call_handler.speak('Please wait while we connect you to the radio station', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) self.__request_station_call() self.__in_talkshow_setup = False elif dtmf_digit == "2" and self.__in_talkshow_setup: # stop the music, put this live on air self.program.log_program_activity("Host is not ready. We will hangup Arghhh!") self.hangup_call() self.__in_talkshow_setup = False elif dtmf_digit == "1": # Wake mode, the station will wake host when someone calls in and host is off air if self.__phone_status != PhoneStatus.WAKE: self.__phone_status = PhoneStatus.WAKE self.__call_handler.speak('Your call will be terminated and you will be called when someone calls into the station', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) self.hangup_call() else: self.__phone_status = PhoneStatus.REJECTING self.__call_handler.speak('All incoming calls will be rejected', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) elif dtmf_digit == "3": # put the station =in auto_answer if self.__phone_status != PhoneStatus.ANSWERING: self.__phone_status = PhoneStatus.ANSWERING self.__call_handler.speak('All incoming calls will be automatically answered', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) else: self.__phone_status = PhoneStatus.REJECTING self.__call_handler.speak('All incoming calls will be rejected', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) elif dtmf_digit == "4": # disable auto answer, reject and record all incoming calls if self.__phone_status != PhoneStatus.QUEUING: self.__phone_status = PhoneStatus.QUEUING self.__call_handler.speak( 'All incoming calls will be queued for call back', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) else: self.__phone_status = PhoneStatus.REJECTING self.__call_handler.speak( 'All incoming calls will be rejected', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) elif dtmf_digit == "5": # dequeue and call from queue of calls that were queued for caller in self.__interested_participants: result = self.__call_handler.call(self, caller, None, None, self.duration) self.program.log_program_activity("result of participant call is {0}".format(str(result))) self.__community_call_UUIDs[caller] = result[1] self.__call_handler.register_for_call_hangup(self, caller) self.__interested_participants.discard(caller) return elif dtmf_digit == "6": # terminate the current caller for community_call_UUID in self.__community_call_UUIDs: self.__call_handler.hangup(self.__community_call_UUIDs[community_call_UUID]) pass elif dtmf_digit == "7": # terminate the current caller (invitee) for invitee_call_key in self.__invitee_call_UUIDs: self.__call_handler.hangup(self.__invitee_call_UUIDs[invitee_call_key]) pass elif dtmf_digit == "9": # Take a 5 min music break self.__call_handler.speak('You will be called back in 5 minutes', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) self.program.log_program_activity("Host is taking a break") self.__pause_call() else: if dtmf_digit == "#": # Call invitee number if self.__invitee_number == "": self.__call_handler.speak('Please enter the number to call and press the # key to dial', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) else: self.__call_handler.speak('You are calling {0}'.format(self.__invitee_number), self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) result = self.__call_handler.call(self, self.__invitee_number, self.__host.phone.raw_number, False, self.duration) self.__call_handler.register_for_call_hangup(self, self.__invitee_number) if result[0]: self.__invitee_call_UUIDs[self.__invitee_number] = result[1] else: self.__call_handler.speak('The call to {0} failed. Please pres the hash key to try again'.format(self.__invitee_number), self.__available_calls[self.__host.phone.raw_number][ 'Channel-Call-UUID']) else: # Collect digits to call self.__invitee_number = "{0}{1}".format(self.__invitee_number, dtmf_digit) def notify_host_call(self, call_info): # hangup the call self.__call_handler.hangup(call_info['Channel-Call-UUID']) # reset program # self.stop() # restart program self.start() def notify_incoming_call(self, call_info): if self.__phone_status == PhoneStatus.ANSWERING: # answer the phone call, join it to the conference if len(self.__community_call_UUIDs) == 0: self.__call_handler.bridge_incoming_call(call_info['Channel-Call-UUID'], "{0}_{1}".format(self.program.id, self.program.radio_station.id)) self.__call_handler.register_for_call_hangup(self, call_info['Caller-Destination-Number']) self.__community_call_UUIDs[call_info['Caller-Destination-Number']] = call_info['Channel-Call-UUID'] self.program.log_program_activity( "Call from community caller {0} was auto-answered".format(call_info['Caller-Destination-Number'])) elif self.__phone_status == PhoneStatus.QUEUING: # Hangup the phone, call back later self.__interested_participants.add(call_info['Caller-ANI']) self.__call_handler.speak( 'You have a new caller on the line', self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) self.__call_handler.hangup(call_info['Channel-Call-UUID']) self.program.log_program_activity( "Call from community caller {0} was queued".format(call_info['Caller-Destination-Number'])) elif self.__phone_status == PhoneStatus.REJECTING: # Hangup the call self.__call_handler.hangup(call_info['Channel-Call-UUID']) self.program.log_program_activity( "Call from community caller {0} was rejected".format(call_info['Caller-Destination-Number'])) elif self.__phone_status == PhoneStatus.WAKE: # Hangup the call if len(self.__community_call_UUIDs) == 0: self.__call_handler.bridge_incoming_call(call_info['Channel-Call-UUID'], "{0}_{1}".format(self.program.id, self.program.radio_station.id)) self.__call_handler.register_for_call_hangup(self, call_info['Caller-Destination-Number']) self.__community_call_UUIDs[call_info['Caller-Destination-Number']] = call_info['Channel-Call-UUID'] self.program.log_program_activity( "Call from community caller {0} was auto-answered".format(call_info['Caller-Destination-Number'])) self.request_host_call() def __schedule_host_callback(self): time_delta = timedelta(seconds=300) # one minutes now = datetime.now() callback_time = now + time_delta self.__scheduler.add_date_job(getattr(self, 'request_host_call'), callback_time) def __schedule_warning(self): time_delta = timedelta(seconds=self.__warning_time) now = datetime.utcnow() warning_time = now + time_delta self.__scheduler.add_date_job(getattr(self, 'warn_number'), warning_time) def __schedule_hangup(self): time_delta = timedelta(seconds=self.duration) now = datetime.utcnow() hangup_time = now + time_delta self.__scheduler.add_date_job(getattr(self, 'hangup_call'), hangup_time) def __deregister_listeners(self): for available_call in self.__available_calls: self.__call_handler.deregister_for_call_hangup(available_call) self.__call_handler.deregister_for_incoming_calls(self) self.__call_handler.deregister_for_incoming_dtmf(str(self.__host.phone.raw_number))
from datetime import datetime from apscheduler.scheduler import Scheduler import fetchandstore sched = Scheduler() sched.start() sched.add_interval_job(fetchandstore.thewholeshebang, minutes=1) while True: pass
class Bus(BotPlugin): def activate(self): super(Bus, self).activate() self.sched = Scheduler(coalesce=True) self.sched.start() @botcmd(split_args_with=' ') def bus(self, mess, args): argsLength = len(args) if argsLength < 2 : route = 49 else : route = args[1] now = arrow.now() t = self.next_buses(*args) buses = [] if t: for bus in t: buses.append( 'No. %s bus leaves from %s %s' % ( route, args[0], bus.humanize(now) ) ) for s in buses: yield s @botcmd(split_args_with=' ') def bus_remind(self, mess, args): t = self.next_bus(*args) reminder = t.replace(minutes=-10) remind = partial(self.remind, mess, args) self.sched.add_date_job(remind, reminder.naive) return "%s: you'll be reminded %s" % ( mess.getMuckNick(), reminder.humanize() ) def remind(self, mess, args): now = arrow.now() t = self.next_bus(args[0], args[1]) if t: self.send( mess.getFrom(), '%s: the next no. %s bus leaves from %s %s' % ( mess.getMuckNick(), args[1], args[0], t.humanize(now) ), message_type=mess.getType() ) def parse_timetable(self, stop, route): if stop in STOPS: stop = STOPS[stop] url = posixpath.join( "http://www.nextbuses.mobi", "WebView/BusStopSearch/BusStopSearchResults/", stop ) res = requests.get( url, params={'searchType': 'route', 'searchFilter': route} ) soup = BeautifulSoup(res.text) bus_stops = soup.findAll('table', {'class': 'BusStops'}) times = bus_stops[0].findAll('p', {'class': 'Stops'}) #should loop instead of return one return times def next_bus(self, stop, route=49, time=0): times = self.parse_timetable(stop, route) now = arrow.now() then = now.replace(minutes=+int(time)) nextbuses = [] for i in times: logging.info(i.text) if 'DUE' in i.text: continue elif ';at ' in i.text: t = i.text.split('at ')[-1].strip().split(':') next = now.replace(hour=int(t[0]), minute=int(t[1])) logging.info(next) else: t = i.text.split('in ')[-1].strip().split() next = now.replace(minutes=int(t[0])) logging.info(next) if next > then: return next return False def next_buses(self,stop, route=49,time=0): times = self.parse_timetable(stop,route) now = arrow.now() then = now.replace(minutes=+int(time)) buses = [] for i in times: logging.info(i.text) if 'DUE' in i.text: continue elif ';at ' in i.text: t = i.text.split('at ')[-1].strip().split(':') if t[1].find('(') == -1: logging.info("replacing hour with %s and minute with %s" % (t[0], t[1])) next = now.replace(hour=int(t[0]), minute=int(t[1])) buses.append(next) logging.info("Next bus parsed is %s" % next) else: t = i.text.split('in ')[-1].strip().split() next = now.replace(minutes=int(t[0])) buses.append(next) logging.info(next) if len(buses) != 0: return buses; return False
import apscheduler from datetime import datetime from apscheduler.scheduler import Scheduler print('in scheduler') def job_function(): email = EmailMsg(12.99, 11.99, 'Title', '*****@*****.**') print('Automated') sched = Scheduler(standalone=True) sched.add_interval_job(job_function, minutes=1) sched.start()
if send_report: report = au.create_report() au.email_report(report) au.save_issues() if jirasync: app.logger.info('Syncing {} issues on {} with Jira'.format( au.index, accounts)) jirasync.sync_issues(accounts, au.index) pool = ThreadPool(core_threads=app.config.get('CORE_THREADS', 25), max_threads=app.config.get('MAX_THREADS', 30), keepalive=0) scheduler = Scheduler(standalone=True, threadpool=pool, coalesce=True, misfire_grace_time=30) def setup_scheduler(): """Sets up the APScheduler""" log = logging.getLogger('apscheduler') log.setLevel(app.config.get('LOG_LEVEL')) log.addHandler(handler) try: accounts = Account.query.filter(Account.third_party == False).filter( Account.active == True).all() accounts = [account.name for account in accounts] for account in accounts: print "Scheduler adding account {}".format(account)
from flask import Flask from flask_restful import Api from resources import * from db import init_db import atexit from apscheduler.scheduler import Scheduler from tasks import check_expired_servers app = Flask(__name__) api = Api(app) cron = Scheduler() cron.add_interval_job(check_expired_servers, seconds=30) cron.start() atexit.register(lambda: cron.shutdown(wait=False)) @app.teardown_appcontext def cleanup(resp_or_exc): Session.remove() api.add_resource(RackResource, '/racks/<string:id>', endpoint='racks') api.add_resource(RackListResource, '/racks/', endpoint='rack') api.add_resource(ServerResource, '/servers/<string:id>', endpoint='servers') api.add_resource(ServerListResource, '/servers/', endpoint='server') if __name__ == '__main__': init_db() app.run(debug=True)
from apscheduler.scheduler import Scheduler FULL_PATH = None RUNDIR = None ARGS = None DAEMON = False PIDFILE = None VERBOSE = True LOG_FILE = None LOG_LIST = [] PORT = None DATABASE = None INIT_LOCK = threading.Lock() __INITIALIZED__ = False DEVELOPMENT = False SCHEDULE = Scheduler() WEBROOT = '' logger = None SERVER = None HOST = '0.0.0.0' KIOSK = False DATA_DIR = None SCRIPT_DIR = None THREADS = [] AUTH = { 'username': None, 'password': None, } UPDATER = True
#!/usr/bin/env python #coding=utf-8 #author: hhr import os, sys, time import comm from apscheduler.scheduler import Scheduler sched = Scheduler(daemonic=False) def job_function(server): os.system('python %ssaltweb/%s.py' % (comm.base_dir, server)) sched.add_interval_job(job_function, hours=1, args=['assets']) sched.add_interval_job(job_function, seconds=60, args=['hostping']) sched.add_interval_job(job_function, minutes=5, args=['monitor']) #sched.add_interval_job(job_function,minutes=1,args=['server']) #sched.add_interval_job(job_function,seconds=120,args=['rrdupdate']) sched.add_interval_job(job_function, minutes=5, args=['urlmonitor']) time.sleep(2) sched.start()
global workersInRegion1min global count if count != 0: workersInRegion1min = numpy.array(workersInRegion1min) // count path = 'C:\\Users\\24330\\Desktop\\Server-Nvr\\database\\info.db' conn = sql.connect(path) timeRecord = datetime.datetime.now(timezone).strftime('%Y-%m-%d %H:%M:%S') mylib.insert_heat(conn, workersInRegion1min[0], workersInRegion1min[1], workersInRegion1min[2], workersInRegion1min[3], workersInRegion1min[4], workersInRegion1min[5], workersInRegion1min[6], workersInRegion1min[7]), workersInRegion1min = [0, 0, 0, 0, 0, 0, 0, 0] conn.commit() sched = Scheduler() # 实例化,固定格式 @sched.interval_schedule(seconds=60) # 装饰器,seconds=60意思为该函数为1分钟运行一次 def mytask(): TableHeatmap() sched.start() # 启动该脚本 def resolveFace(sdata): stringData = sdata.getData() stringLabel = str(sdata.getLabel(), 'utf-8') strjson = "".join([stringLabel.strip().rsplit("}", 1)[0], "}"]) frameinfodata = json.loads(strjson, strict=False)
Python 的 Scheduler 框架是模仿Java的Quartz框架写的,用起来还是比较不错的,这里向大家强烈推荐下。 使用说明: http://pythonhosted.org/APScheduler/index.html 相关API: http://packages.python.org/APScheduler/genindex.html 下载地址: https://pypi.python.org/pypi/APScheduler/ 使用 easy_install 安装: easy_install apscheduler 1. 指定特定时间运行某一任务,可以通过如下方式: from datetime import datetime from apscheduler.scheduler import Scheduler sched = Scheduler() sched.daemonic = False # daemonic参数,表示执行线程是非守护的,在Schduler的文档中推荐使用非守护线程 # 上面两行,也可以简写为: sched = Scheduler(daemonic = False) def job_function(text): print text # 指定时间运行,且只运行一次 job = sched.add_date_job(job_function, datetime(2013, 10, 30, 17, 13, 59), ['Hello World']) sched.start() 2. 有些时候,我们需要每隔一定时间运行一下任务 Interval-based scheduling 的方式,如下: from apscheduler.scheduler import Scheduler
blockchain.add_node(node) response = { 'message': 'All the nodes are now connected. The Bitkhan blockchain contains the following nodes:', 'total_nodes': list(blockchain.nodes) } return jsonify(response), 201 @app.route('/', methods=['GET']) def load_main_page(): return render_template('index.html') # Running the App cron = Scheduler(daemon=True) # Explicitly kick off the background thread cron.start() @cron.interval_schedule(seconds=10) def replace_chain(): is_chain_replaced = blockchain.consensus() #is_chain_replaced = blockchain.replace_chain() if is_chain_replaced: response = { 'message': 'The Blockchain was replaced by the longest chain', 'new_chain': blockchain.chain } else: response = {
from flask import Flask, jsonify, request, make_response from apscheduler.scheduler import Scheduler import urllib import json import os #Librerias Web Scraping from bs4 import BeautifulSoup import urllib.request import re import requests import pandas as pd import atexit app = Flask(__name__) cron = Scheduler(daemon=True) # Explicitly kick off the background thread cron.start() @cron.interval_schedule(hours=2) def scrapBCV(): url = "http://www.bcv.org.ve" page = urllib.request.urlopen(url) soup = BeautifulSoup(page, 'html.parser') regex = re.compile('^') content_lis = soup.find("div", {"id": "dolar"}) content_date = soup.find("span", {"class" :"date-display-single"}) fecha = content_date.text dolar = content_lis.div.strong.text.strip() imp = print('Dolar BCV : {} para la fecha : {}'.format(dolar, fecha)) bcv = {
def scheduler_start(self): if not PeriodicTimer.sched: PeriodicTimer.sched = Scheduler() if not PeriodicTimer.sched.running: PeriodicTimer.sched.start()
API_CRT = "utils/Certificates/server.crt" API_KEY = "utils/Certificates/server.key" HTTPS_ENABLED = True VERIFY_USER = True API_HOST = config_properties['host'] API_PORT = config_properties['port'] RECOMMENDATION_COUNT = config_properties['recommendations_count'] SEARCH_DETAILS_VALID_TIME = config_properties['search_details_valid_months'] MINIMUM_SEARCH_QUERIES = config_properties['minimum_search_queries'] MONGODB_URL = config_properties['mongodb_url'] cron = Scheduler(daemon=True) app = flask.Flask(__name__) app.config['BASIC_AUTH_USERNAME'] = config_properties['username'] app.config['BASIC_AUTH_PASSWORD'] = config_properties['password'] basic_auth = BasicAuth(app) @cron.interval_schedule(hours=24) def update_user_recommendations_db(): """ Processing recommendations periodically with a time interval of 24 hours and storing them in a db so that these pre-processed recommendations can be retrieved whenever needed. """ try: process_user_info(SEARCH_DETAILS_VALID_TIME, MINIMUM_SEARCH_QUERIES)
import requests from apscheduler.scheduler import Scheduler #Current Season CURRENT_SEASON = "20182019" player_info_url = "http://www.nhl.com/stats/rest/skaters?isAggregate=false&reportType=basic&isGame=false&reportName=skatersummary&sort=[{%22property%22:%22points%22,%22direction%22:%22DESC%22},{%22property%22:%22goals%22,%22direction%22:%22DESC%22},{%22property%22:%22assists%22,%22direction%22:%22DESC%22}]&cayenneExp=gameTypeId=2%20and%20seasonId%3E=" + CURRENT_SEASON + "%20and%20seasonId%3C=" + CURRENT_SEASON goalie_info_url = "http://www.nhl.com/stats/rest/goalies?isAggregate=false&reportType=goalie_basic&isGame=false&reportName=goaliesummary&sort=[{%22property%22:%22wins%22,%22direction%22:%22DESC%22}]&cayenneExp=gameTypeId=2%20and%20seasonId%3E=" + CURRENT_SEASON + "%20and%20seasonId%3C=" + CURRENT_SEASON player_data = requests.get(player_info_url).json() goalie_data = requests.get(goalie_info_url).json() #ScheduleStuff sched = Scheduler() sched.start() def update(): global player_data player_data = requests.get(player_info_url).json() global goalie_data goalie_data = requests.get(goalie_info_url).json() sched.add_interval_job(update, hours=6) #ID STUFF team_name_to_id = { 'devils': '01', 'islanders': '02', 'islies': '02', 'rangers': '03',
def activate(self): super(Bus, self).activate() self.sched = Scheduler(coalesce=True) self.sched.start()
class Scheduler(Plugin): crons = {} intervals = {} started = False def __init__(self): addEvent('schedule.cron', self.cron) addEvent('schedule.interval', self.interval) addEvent('schedule.remove', self.remove) self.sched = Sched(misfire_grace_time=60) self.sched.start() self.started = True def remove(self, identifier): for cron_type in ['intervals', 'crons']: try: self.sched.unschedule_job( getattr(self, cron_type)[identifier]['job']) log.debug('%s unscheduled %s', (cron_type.capitalize(), identifier)) except: pass def doShutdown(self): super(Scheduler, self).doShutdown() self.stop() def stop(self): if self.started: log.debug('Stopping scheduler') self.sched.shutdown() log.debug('Scheduler stopped') self.started = False def cron(self, identifier='', handle=None, day='*', hour='*', minute='*'): log.info('Scheduling "%s", cron: day = %s, hour = %s, minute = %s', (identifier, day, hour, minute)) self.remove(identifier) self.crons[identifier] = { 'handle': handle, 'day': day, 'hour': hour, 'minute': minute, 'job': self.sched.add_cron_job(handle, day=day, hour=hour, minute=minute) } def interval(self, identifier='', handle=None, hours=0, minutes=0, seconds=0): log.info( 'Scheduling %s, interval: hours = %s, minutes = %s, seconds = %s', (identifier, hours, minutes, seconds)) self.remove(identifier) self.intervals[identifier] = { 'handle': handle, 'hours': hours, 'minutes': minutes, 'seconds': seconds, 'job': self.sched.add_interval_job(handle, hours=hours, minutes=minutes, seconds=seconds) }
def __init__(self, **kwargs): self.schedudler = Scheduler(daemonic=kwargs['daemonic'])
def stop(self): if not self.__scheduler is None: self.__scheduler.shutdown(wait=False) self.__scheduler = Scheduler(self.APS_CONFIG) logger.info("[AlertScheduler] Stopped the alert scheduler.")
os.remove(workingDir + file) if status == 1: loggerUpdate.info("Update: Inside Battery " + str(dataValue)) if "TOBATT" in file: status = updateDB(str(dataValue), 'outsidebatt') os.remove(workingDir + file) if status == 1: loggerUpdate.info("Update: Outside Battery " + str(dataValue)) if "THBATT" in file: status = updateDB(str(dataValue), 'solarbatt') os.remove(workingDir + file) if status == 1: loggerUpdate.info("Update: Solar Battery " + str(dataValue)) scheduler = Scheduler() scheduler.add_interval_job(bmp085, minutes=3) scheduler.add_interval_job(checkfiles, minutes=1) scheduler.add_interval_job(checkRelay, seconds=3) scheduler.add_interval_job(relayStatus, minutes=3) scheduler.start() while True: c = serial.read() while c != 'a': c = serial.read() llapMsg = "a" + serial.read(11) loggerSerial.info("Received " + llapMsg) deviceID = llapMsg[1:3] if llapMsg == 'aRFxxxxxxx-': serial.write('aRFOPENLOCK-')
class AlertSchedulerHandler(): TYPE_PORT = 'PORT' TYPE_METRIC = 'METRIC' TYPE_AMS = 'AMS' TYPE_SCRIPT = 'SCRIPT' TYPE_WEB = 'WEB' TYPE_RECOVERY = 'RECOVERY' def __init__(self, initializer_module, in_minutes=True): self.cachedir = initializer_module.config.alerts_cachedir self.stacks_dir = initializer_module.config.stacks_dir self.common_services_dir = initializer_module.config.common_services_dir self.extensions_dir = initializer_module.config.extensions_dir self.host_scripts_dir = initializer_module.config.host_scripts_dir self.configuration_builder = initializer_module.configuration_builder self._cluster_configuration = initializer_module.configurations_cache self.alert_definitions_cache = initializer_module.alert_definitions_cache self.config = initializer_module.config # the amount of time, in seconds, that an alert can run after it's scheduled time alert_grace_period = int(self.config.get('agent', 'alert_grace_period', 5)) apscheduler_standalone = False self.APS_CONFIG = { 'apscheduler.threadpool.core_threads': 3, 'apscheduler.coalesce': True, 'apscheduler.standalone': apscheduler_standalone, 'apscheduler.misfire_grace_time': alert_grace_period, 'apscheduler.threadpool.context_injector': self._job_context_injector if not apscheduler_standalone else None, 'apscheduler.threadpool.agent_config': self.config } self._collector = AlertCollector() self.__scheduler = Scheduler(self.APS_CONFIG) self.__in_minutes = in_minutes self.recovery_manger = initializer_module.recovery_manager # register python exit handler ExitHelper().register(self.exit_handler) def _job_context_injector(self, config): """ apscheduler hack to inject monkey-patching, context and configuration to all jobs inside scheduler in case if scheduler running in embedded mode Please note, this function called in job context thus all injects should be time-running optimized :type config AmbariConfig.AmbariConfig """ if not config.use_system_proxy_setting(): from ambari_commons.network import reconfigure_urllib2_opener reconfigure_urllib2_opener(ignore_system_proxy=True) def exit_handler(self): """ Exit handler """ self.stop() def update_definitions(self, event_type): """ Updates the persisted alert definitions JSON. :return: """ # prune out things we don't want to store alert_definitions = [] for cluster_id, command in self.alert_definitions_cache.iteritems(): command_copy = Utils.get_mutable_copy(command) alert_definitions.append(command_copy) if event_type == "CREATE": # reschedule all jobs, creating new instances self.reschedule_all() else: # reschedule only the jobs that have changed self.reschedule() def __make_function(self, alert_def): return lambda: alert_def.collect() def start(self): """ loads definitions from file and starts the scheduler """ if self.__scheduler is None: return if self.__scheduler.running: self.__scheduler.shutdown(wait=False) self.__scheduler = Scheduler(self.APS_CONFIG) alert_callables = self.__load_definitions() # schedule each definition for _callable in alert_callables: self.schedule_definition(_callable) logger.info("[AlertScheduler] Starting {0}; currently running: {1}".format( str(self.__scheduler), str(self.__scheduler.running))) self.__scheduler.start() def stop(self): if not self.__scheduler is None: self.__scheduler.shutdown(wait=False) self.__scheduler = Scheduler(self.APS_CONFIG) logger.info("[AlertScheduler] Stopped the alert scheduler.") def reschedule(self): """ Removes jobs that are scheduled where their UUID no longer is valid. Schedules jobs where the definition UUID is not currently scheduled. """ jobs_scheduled = 0 jobs_removed = 0 definitions = self.__load_definitions() scheduled_jobs = self.__scheduler.get_jobs() # for every scheduled job, see if its UUID is still valid for scheduled_job in scheduled_jobs: uuid_valid = False for definition in definitions: definition_uuid = definition.get_uuid() if scheduled_job.name == definition_uuid: uuid_valid = True break # jobs without valid UUIDs should be unscheduled if uuid_valid is False: jobs_removed += 1 logger.info("[AlertScheduler] Unscheduling {0}".format(scheduled_job.name)) self._collector.remove_by_uuid(scheduled_job.name) self.__scheduler.unschedule_job(scheduled_job) # for every definition, determine if there is a scheduled job for definition in definitions: definition_scheduled = False for scheduled_job in scheduled_jobs: definition_uuid = definition.get_uuid() if definition_uuid == scheduled_job.name: definition_scheduled = True break # if no jobs are found with the definitions UUID, schedule it if definition_scheduled is False: jobs_scheduled += 1 self.schedule_definition(definition) logger.info("[AlertScheduler] Reschedule Summary: {0} rescheduled, {1} unscheduled".format( str(jobs_scheduled), str(jobs_removed))) def reschedule_all(self): """ Removes jobs that are scheduled where their UUID no longer is valid. Schedules jobs where the definition UUID is not currently scheduled. """ logger.info("[AlertScheduler] Rescheduling all jobs...") jobs_scheduled = 0 jobs_removed = 0 definitions = self.__load_definitions() scheduled_jobs = self.__scheduler.get_jobs() # unschedule all scheduled jobs for scheduled_job in scheduled_jobs: jobs_removed += 1 logger.info("[AlertScheduler] Unscheduling {0}".format(scheduled_job.name)) self._collector.remove_by_uuid(scheduled_job.name) self.__scheduler.unschedule_job(scheduled_job) # for every definition, schedule a job for definition in definitions: jobs_scheduled += 1 self.schedule_definition(definition) logger.info("[AlertScheduler] Reschedule Summary: {0} unscheduled, {0} rescheduled".format( str(jobs_removed), str(jobs_scheduled))) def collector(self): """ gets the collector for reporting to the server """ return self._collector def __load_definitions(self): """ Loads all alert definitions from a file. All clusters are stored in a single file. This wil also populate the cluster-to-hash dictionary. :return: """ definitions = [] for cluster_id, command_json in self.alert_definitions_cache.iteritems(): clusterName = '' if not 'clusterName' in command_json else command_json['clusterName'] hostName = '' if not 'hostName' in command_json else command_json['hostName'] publicHostName = '' if not 'publicHostName' in command_json else command_json['publicHostName'] clusterHash = None if not 'hash' in command_json else command_json['hash'] # cache the cluster and cluster hash after loading the JSON if clusterName != '' and clusterHash is not None: logger.info('[AlertScheduler] Caching cluster {0} with alert hash {1}'.format(clusterName, clusterHash)) for definition in command_json['alertDefinitions']: alert = self.__json_to_callable(clusterName, hostName, publicHostName, Utils.get_mutable_copy(definition)) if alert is None: continue alert.set_helpers(self._collector, self._cluster_configuration, self.configuration_builder) definitions.append(alert) return definitions def __json_to_callable(self, clusterName, hostName, publicHostName, json_definition): """ converts the json that represents all aspects of a definition and makes an object that extends BaseAlert that is used for individual """ alert = None try: source = json_definition['source'] source_type = source.get('type', '') if logger.isEnabledFor(logging.DEBUG): logger.debug("[AlertScheduler] Creating job type {0} with {1}".format(source_type, str(json_definition))) if source_type == AlertSchedulerHandler.TYPE_METRIC: alert = MetricAlert(json_definition, source, self.config) elif source_type == AlertSchedulerHandler.TYPE_AMS: alert = AmsAlert(json_definition, source, self.config) elif source_type == AlertSchedulerHandler.TYPE_PORT: alert = PortAlert(json_definition, source, self.config) elif source_type == AlertSchedulerHandler.TYPE_SCRIPT: source['stacks_directory'] = self.stacks_dir source['common_services_directory'] = self.common_services_dir source['extensions_directory'] = self.extensions_dir source['host_scripts_directory'] = self.host_scripts_dir alert = ScriptAlert(json_definition, source, self.config) elif source_type == AlertSchedulerHandler.TYPE_WEB: alert = WebAlert(json_definition, source, self.config) elif source_type == AlertSchedulerHandler.TYPE_RECOVERY: alert = RecoveryAlert(json_definition, source, self.config, self.recovery_manger) if alert is not None: alert.set_cluster(clusterName, json_definition['clusterId'], hostName, publicHostName) except Exception, exception: logger.exception("[AlertScheduler] Unable to load an invalid alert definition. It will be skipped.") return alert
parser = OptionParser(description='a crawer which get jobs info.') parser.add_option('-s', '--sms', dest='sms', action='store_true', help='send sms mode') parser.add_option('-e', '--email', dest='email', action='store_true', help='send email mode') (options, args) = parser.parse_args(args=sys.argv[1:]) crawler = Crawler() crawler.run() sched = Scheduler() sched.start() sched.add_interval_job(crawler.run, hours=CRAWLER_FREQUENCE_HOURS) sched.add_interval_job(crawler.send_massage, minutes=MESSAGE_FREQUENCE_MINUTES, kwargs=options.__dict__) try: print "start server ..." server = HTTPServer((HOST_NAME, PORT_NUMBER), HttpHandler) server.serve_forever() except KeyboardInterrupt: print "finish server ..." server.socket.close()
class RadioProgram: def __init__(self, program, radio_station, program_handler): self.__rootio_mail_message = RootIOMailMessage() self.__program_actions = [] self.__status = False self.__call_info = None self.id = program.id self.name = program.id self.__program_handler = program_handler self.scheduled_program = program self.radio_station = radio_station self.__shutting_down = False self.__scheduler = Scheduler() self.__running_action = None return def start(self): self.__load_program_actions() if len(self.__program_actions) == 0: return else: self.__program_handler.set_running_program(self) self.__run_program_action() # will call the next one when done ''' Load the definition of components of the program from a JSON definition ''' def __load_program_actions(self): try: data = json.loads(self.scheduled_program.program.structure) except ValueError as e: print e return for action in data: if "type" in action: if action['type'] == "Advertisements": if "track_id" in action and "start_time" in action and "duration" in action: self.__program_actions.insert(0, AdvertisementAction(action["track_id"], action["start_time"], action["duration"], self)) self.radio_station.logger.info( "Advertisements program scheduled to start at {0} for a duration {1}".format(action["start_time"], action["duration"])) if action['type'] == "Media": if "track_id" in action and "start_time" in action and "duration" in action: self.__program_actions.insert(0, MediaAction(action["track_id"], action["start_time"], action["duration"], self)) self.radio_station.logger.info( "Media program scheduled to start at {0} for a duration {1}".format(action["start_time"], action["duration"])) if action['type'] == "Community": if "category_id" in action and "start_time" in action and "duration" in action: self.__program_actions.insert(0, CommunityAction(action["category_id"], action["start_time"], action["duration"], self)) self.radio_station.logger.info( "Community program scheduled to start at {0} for a duration {1}".format(action["start_time"], action["duration"])) if action['type'] == "Podcast": if "track_id" in action and "start_time" in action and "duration" in action: self.__program_actions.insert(0, PodcastAction(action["track_id"], action["start_time"], action["duration"], self)) self.radio_station.logger.info( "Podcast program scheduled to start at {0} for a duration {1}".format(action["start_time"], action["duration"])) if action['type'] == "Music": if "start_time" in action and "duration" in action: self.radio_station.logger.info( "Music program scheduled to start at {0} for a duration {1}".format(action["start_time"], action["duration"])) if action['type'] == "News": if "track_id" in action and "start_time" in action and "duration" in action: self.__program_actions.insert(0, NewsAction(action["track_id"], action["start_time"], action["duration"], self)) self.radio_station.logger.info( "News program scheduled to start at {0} for a duration {1}".format(action["start_time"], action["duration"])) if action['type'] == "Outcall": if "host_id" in action and "start_time" in action and "duration" in action: self.__program_actions.insert(0, OutcallAction(action['host_id'], action["start_time"], action['duration'], self)) self.radio_station.logger.info( "Outcall program scheduled to start at {0} for a duration {1}".format(action["start_time"], action["duration"])) return ''' Schedule the actions of a particular program for playback within the program ''' def __schedule_program_actions(self): for program_action in self.__program_actions: self.__scheduler.add_date_job(getattr(program_action, 'start'), self.__get_start_datetime(program_action.start_time).replace(tzinfo=None), misfire_grace_time=program_action.duration) def stop(self): self.__shutting_down = True if self.__running_action is not None: self.__running_action.stop() def set_running_action(self, running_action): #if self.__running_action is not None: # self.__running_action.stop() # clean up any stuff that is not necessary anymore self.__running_action = running_action def log_program_activity(self, program_activity): self.radio_station.logger.info(program_activity) self.__rootio_mail_message.append_to_body( '%s %s' % (datetime.now().strftime('%y-%m-%d %H:%M:%S'), program_activity)) def __run_program_action(self): if self.__program_actions is not None and len(self.__program_actions) > 0: self.radio_station.logger.info("Popping program action from program actions: {0}".format(self.__program_actions)) self.__program_actions.pop().start() def notify_program_action_stopped(self, played_successfully, call_info): # the next action might need the call. if self.__shutting_down: self.radio_station.logger.info("Shutting down this program...") self.__status = self.__status or played_successfully self.radio_station.call_handler.hangup(call_info['Channel-Call-UUID']) self.__log_program_status() else: self.__status = self.__status or played_successfully # For program with multiple actions, if one succeeds then flagged as success! if call_info is not None and 'Channel-Call-UUID' in call_info: self.__call_info = call_info if len(self.__program_actions) == 0: # all program actions have run self.radio_station.logger.info("Program actions array is empty. Program will terminate") if self.__call_info is not None: self.radio_station.call_handler.hangup(self.__call_info['Channel-Call-UUID']) self.__log_program_status() self.__send_program_summary() else: self.__run_program_action() def __send_program_summary(self): try: self.__rootio_mail_message.set_subject( '[%s] %s ' % (self.radio_station.station.name, self.scheduled_program.program.name)) self.__rootio_mail_message.set_from('*****@*****.**') # This will come from DB in future users = self.__get_network_users() for user in users: if user.receive_station_notifications: self.__rootio_mail_message.add_to_address(user.email) self.__rootio_mail_message.send_message() except Exception as e: self.radio_station.logger.error("Error {er} in send program summary for {prg}".format(er=str(e), prg=self.scheduled_program.program.name)) def __log_program_status(self): try: conn = psycopg2.connect(DefaultConfig.SQLALCHEMY_DATABASE_URI) cur = conn.cursor() cur.execute("update radio_scheduledprogram set status = %s where id = %s", (self.__status, self.scheduled_program.id)) conn.commit() except psycopg2.Error as e: try: self.radio_station.logger.error("Error(1) {err} in radio_program.__log_program_status".format(err=e.message)) except Exception as e: return except Exception as e: self.radio_station.logger.error("Error(3) {err} in radio_program.__log_program_status".format(err=e.message)) finally: try: cur.close() conn.close() except Exception as e: self.radio_station.logger.error( "Error(4) {err} in radio_program.__log_program_status".format(err=e.message)) def __get_network_users(self): station_users = self.radio_station.station.network.networkusers return station_users ''' Get the time at which to schedule the program action to start ''' def __get_start_datetime(self, time_part): now = datetime.now(dateutil.tz.tzlocal()) t = datetime.strptime(time_part, "%H:%M:%S") time_delta = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second) return now + time_delta + timedelta(seconds=2) # 2 second scheduling allowance
class OutcallAction: def __init__(self, host_id, start_time, duration, program): self.__host_id = host_id self.start_time = start_time self.duration = duration self.program = program self.__scheduler = None self.__available_calls = dict() self.__in_talkshow_setup = False self.__host = None self.__community_call_UUIDs = dict() self.__invitee_call_UUIDs = dict() self.__call_handler = self.program.radio_station.call_handler self.__phone_status = PhoneStatus.QUEUING self.__interested_participants = Set([]) self.__collecting_digits_to_call = False self.__invitee_number = "" self.__prompt_engine = PromptEngine(self.program.radio_station) def start(self): try: self.__in_talkshow_setup = True self.__host = self.__get_host(self.__host_id) if self.__host is None or self.__host.phone is None: self.stop(PlayStatus.no_media) return self.program.set_running_action(self) self.__scheduler = Scheduler() self.__scheduler.start() self.__call_handler.register_for_incoming_calls(self) self.__call_handler.register_for_incoming_dtmf( self, str(self.__host.phone.raw_number)[-9:]) self.__call_handler.register_for_host_call( self, str(self.__host.phone.raw_number)[-9:]) self.request_host_call() except Exception as e: self.program.log_program_activity( "Error in OutcallAction.start: {0}".format(e.message)) print e def stop(self, graceful=PlayStatus.success, call_info=None): self.hangup_call() # Stop scheduler self.__scheduler.shutdown() # deregister from any triggers self.__call_handler.deregister_for_incoming_calls(self) self.__call_handler.deregister_for_incoming_dtmf( str(self.__host.phone.raw_number)[-9:]) self.program.notify_program_action_stopped(graceful, call_info) def __get_host(self, host_id): host = self.program.radio_station.db.query(Person).filter( Person.id == host_id).first() return host def request_host_call(self, guest_triggered=False): self.__in_talkshow_setup = True result = self.__call_handler.call(self, self.__host.phone.raw_number, None, False, 15) # call ends in 15 mins max self.program.log_program_activity("result of host call is " + str(result)) if not result[0] and not guest_triggered: self.stop(PlayStatus.failed) def __request_station_call(self): # call the number specified thru plivo # Check if the call exists, start with the least likely number to be called if self.program.radio_station.station.secondary_transmitter_phone is not None and self.__call_handler.call_exists( self.program.radio_station.station.secondary_transmitter_phone. raw_number): result = self.__call_handler.call( self, self.program.radio_station.station. secondary_transmitter_phone.raw_number, self.program.name, False, self.duration) return result elif self.program.radio_station.station.primary_transmitter_phone is not None and self.__call_handler.call_exists( self.program.radio_station.station.primary_transmitter_phone. raw_number): result = self.__call_handler.call( self, self.program.radio_station.station. primary_transmitter_phone.raw_number, self.program.name, False, self.duration) return result elif self.program.radio_station.station.sip_username is not None and self.__call_handler.call_exists( self.program.radio_station.station.sip_username): result = self.__call_handler.call( self, self.program.radio_station.station.sip_username, self.program.name, True, self.duration) self.program.log_program_activity( "result of station call via SIP is " + str(result)) return result # At this point we are sure that no call to the station exists. We will try to initiate a new call if self.program.radio_station.station.is_high_bandwidth: result = self.__call_station_via_sip() if result is None or not result[ 0]: # Now try calling the SIM (ideally do primary, then secondary) result = self.__call_station_via_goip() else: result = self.__call_station_via_goip() return result def __call_station_via_sip(self): result = None # Try a high bandwidth call first if self.program.radio_station.station.sip_username is not None: result = self.__call_handler.call( self, self.program.radio_station.station.sip_username, self.__host.phone.raw_number, True, self.duration) self.program.log_program_activity( "result of station call via SIP is " + str(result)) return result def __call_station_via_goip(self): result = None if self.program.radio_station.station.primary_transmitter_phone is not None: result = self.__call_handler.call( self, self.program.radio_station.station. primary_transmitter_phone.raw_number, self.__host.phone.raw_number, False, self.duration) self.program.log_program_activity( "result of station call (primary) via GoIP is " + str(result)) if not result[ 0] and self.program.radio_station.station.secondary_transmitter_phone is not None: # Go for the secondary line of the station, if duo SIM phone result = self.__call_handler.call( self, self.program.radio_station.station. secondary_transmitter_phone.raw_number, self.__host.phone.raw_number, False, self.duration) self.program.log_program_activity( "result of station call (secondary) via GoIP is " + str(result)) return result def notify_call_answered(self, answer_info): if self.__host.phone.raw_number not in self.__available_calls: self.__available_calls[answer_info['Caller-Destination-Number'] [-12:]] = answer_info self.__inquire_host_readiness() self.program.log_program_activity("host call has been answered") elif 'Caller-Destination-Number' in answer_info and answer_info[ 'Caller-Destination-Number'][-12:] == self.__invitee_number: self.__available_calls[answer_info['Caller-Destination-Number'] [-12:]] = answer_info self.__invitee_number = "" self.__collecting_digits_to_call = False else: # This notification is from station answering call self.__available_calls[answer_info['Caller-Destination-Number'] [-12:]] = answer_info self.__prompt_engine.play_prompt( self.__prompt_engine.ON_AIR_PROMPT, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) #self.__call_handler.speak('You are now on air', #self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) # result1 = self.__schedule_warning() # result2 = self.__schedule_hangup() self.__call_handler.register_for_call_hangup( self, answer_info['Caller-Destination-Number'][-12:]) def warn_number(self): seconds = self.duration - self.__warning_time if self.__host.phone.raw_number in self.__available_calls and 'Channel-Call-UUID' in self.__available_calls[ self.__host.phone.raw_number]: result = self.__prompt_engine.play_prompt( self.__prompt_engine.CALL_END_WARNING, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) #result = self.__call_handler.speak( #'Your call will end in ' + str(seconds) + 'seconds', #self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) self.program.log_program_activity("result of warning is " + result) def __pause_call(self): # hangup and schedule to call later self.__schedule_host_callback() self.hangup_call() def notify_call_hangup(self, event_json): if 'Caller-Destination-Number' in event_json: if event_json[ 'Caller-Destination-Number'] in self.__community_call_UUIDs: # a community caller is hanging up del self.__community_call_UUIDs[ event_json['Caller-Destination-Number']] self.__call_handler.deregister_for_call_hangup( event_json['Caller-Destination-Number']) elif event_json[ 'Caller-Destination-Number'] in self.__invitee_call_UUIDs: del self.__invitee_call_UUIDs[ event_json['Caller-Destination-Number']] self.__call_handler.deregister_for_call_hangup( event_json['Caller-Destination-Number']) elif event_json['Caller-Destination-Number'] == self.__host.phone.raw_number or \ event_json['Caller-Destination-Number'] == self.program.radio_station.station.sip_username or \ (self.program.radio_station.station.primary_transmitter_phone is not None and event_json['Caller-Destination-Number'] == self.program.radio_station.station.primary_transmitter_phone.raw_number) or \ (self.program.radio_station.station.secondary_transmitter_phone is not None and event_json['Caller-Destination-Number'] == self.program.radio_station.station.secondary_transmitter_phone.raw_number): # It is a hangup by # the station or the host self.program.log_program_activity( "Program terminated because {0} hangup".format( event_json['Caller-Destination-Number'])) self.stop(PlayStatus.success) def __inquire_host_readiness(self): if self.__phone_status == PhoneStatus.WAKE: self.__prompt_engine.play_prompt( self.__prompt_engine.CALLER_ON_THE_LINE, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) #self.__call_handler.speak( #'You have a caller on the line. To connect to the station, press one, to cancel, press two', #self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) else: self.__prompt_engine.play_prompt( self.__prompt_engine.INQUIRE_HOST_READY, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) #self.__call_handler.speak( #'You are scheduled to host a talk show at this time. If you are ready, press one, if not ready, press two', #self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) self.program.log_program_activity("Asking if host is ready") def hangup_call(self): # hangup the ongoing call for available_call in self.__available_calls: self.__call_handler.deregister_for_call_hangup(available_call) self.__call_handler.hangup( self.__available_calls[available_call]['Channel-Call-UUID']) self.__available_calls = dict( ) # empty available calls. they all are hung up def notify_incoming_dtmf(self, dtmf_info): dtmf_json = dtmf_info dtmf_digit = dtmf_json["DTMF-Digit"] if dtmf_digit == "*": # enter a number to be called followed by the # key self.__collecting_digits_to_call = not self.__collecting_digits_to_call if not self.__collecting_digits_to_call: self.__invitee_number = "" elif not self.__collecting_digits_to_call: if dtmf_digit == "1" and self.__in_talkshow_setup: self.program.log_program_activity( "Host is ready, we are calling the station") self.__prompt_engine.play_prompt( self.__prompt_engine.AWAIT_STATION_CONNECTION, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) self.__request_station_call() self.__in_talkshow_setup = False elif dtmf_digit == "2" and self.__in_talkshow_setup: # stop the music, put this live on air self.program.log_program_activity( "Host is not ready. We will hangup Arghhh!") self.hangup_call() self.__in_talkshow_setup = False elif dtmf_digit == "1": # Wake mode, the station will wake host when someone calls in and host is off air if self.__phone_status != PhoneStatus.WAKE: self.__phone_status = PhoneStatus.WAKE self.__prompt_engine.play_prompt( self.__prompt_engine.ENTERING_WAKE_MODE, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) time.sleep(5) self.hangup_call() else: self.__phone_status = PhoneStatus.REJECTING self.__prompt_engine.play_prompt( self.__prompt_engine.ENTERING_REJECT_MODE, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) elif dtmf_digit == "3": # put the station =in auto_answer if self.__phone_status != PhoneStatus.ANSWERING: self.__phone_status = PhoneStatus.ANSWERING self.__prompt_engine.play_prompt( self.__prompt_engine.ENTERING_AUTO_ANSWER_MODE, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) else: self.__phone_status = PhoneStatus.REJECTING self.__prompt_engine.play_prompt( self.__prompt_engine.ENTERING_REJECT_MODE, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) elif dtmf_digit == "4": # disable auto answer, reject and record all incoming calls if self.__phone_status != PhoneStatus.QUEUING: self.__phone_status = PhoneStatus.QUEUING self.__prompt_engine.play_prompt( self.__prompt_engine.ENTERING_QUEUING_MODE, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) else: self.__phone_status = PhoneStatus.REJECTING self.__prompt_engine.play_prompt( self.__prompt_engine.ENTERING_REJECT_MODE, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) elif dtmf_digit == "5": # dequeue and call from queue of calls that were queued for caller in self.__interested_participants: result = self.__call_handler.call(self, caller, None, None, self.duration) self.program.log_program_activity( "result of participant call is {0}".format( str(result))) self.__community_call_UUIDs[caller] = result[1] self.__call_handler.register_for_call_hangup(self, caller) self.__interested_participants.discard(caller) return elif dtmf_digit == "6": # terminate the current caller for community_call_UUID in self.__community_call_UUIDs: self.__call_handler.hangup( self.__community_call_UUIDs[community_call_UUID]) pass elif dtmf_digit == "7": # terminate the current caller (invitee) for invitee_call_key in self.__invitee_call_UUIDs: self.__call_handler.hangup( self.__invitee_call_UUIDs[invitee_call_key]) pass elif dtmf_digit == "9": # Take a 5 min music break self.__prompt_engine.play_prompt( self.__prompt_engine.ENTERING_5_MIN_BREAK, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) self.program.log_program_activity("Host is taking a break") self.__pause_call() else: if dtmf_digit == "#": # Call invitee number if self.__invitee_number == "": self.__prompt_engine.play_prompt( self.__prompt_engine.ENTER_NUMBER_TO_CALL, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) else: self.__prompt_engine.play_prompt( self.__prompt_engine.CALLING_OUT, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) # CARLOS - Should the phone number be passed here - prompt engine?? #self.__call_handler.speak('You are calling "{0}"'.format(self.__invitee_number), # self.__available_calls[self.__host.phone.raw_number]['Channel-Call-UUID']) result = self.__call_handler.call( self, self.__invitee_number, self.__host.phone.raw_number, False, self.duration) self.__call_handler.register_for_call_hangup( self, self.__invitee_number) if result[0]: self.__invitee_call_UUIDs[ self.__invitee_number] = result[1] # Disable this mode self.__phone_status = PhoneStatus.REJECTING else: # CARLOS TODO - Have to format this! self.__prompt_engine.play_prompt( self.__prompt_engine.CALL_FAILED, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number] ['Channel-Call-UUID']) #self.__call_handler.speak('The call to {0} failed. Please pres the hash key to try again'.format(self.__invitee_number), # self.__available_calls[self.__host.phone.raw_number][ # 'Channel-Call-UUID']) else: # Collect digits to call self.__invitee_number = "{0}{1}".format( self.__invitee_number, dtmf_digit) def notify_host_call(self, call_info): # accept then hangup the call self.__call_handler.bridge_incoming_call( call_info['Channel-Call-UUID'], "temp") self.__call_handler.hangup(call_info['Channel-Call-UUID']) sleep(10) # reset program # self.stop() # restart program self.start() def notify_incoming_call(self, call_info): if self.__phone_status == PhoneStatus.ANSWERING: # answer the phone call, join it to the conference if len(self.__community_call_UUIDs) == 0: self.__call_handler.bridge_incoming_call( call_info['Channel-Call-UUID'], "{0}_{1}".format(self.program.id, self.program.radio_station.id)) self.__call_handler.register_for_call_hangup( self, call_info['Caller-Destination-Number']) self.__community_call_UUIDs[ call_info['Caller-Destination-Number']] = call_info[ 'Channel-Call-UUID'] self.program.log_program_activity( "Call from community caller {0} was auto-answered".format( call_info['Caller-Destination-Number'])) elif self.__phone_status == PhoneStatus.QUEUING: # Hangup the phone, call back later self.__interested_participants.add(call_info['Caller-ANI']) self.__prompt_engine.play_prompt( self.__prompt_engine.INCOMING_CALL_QUEUED, self.__call_handler, self.__available_calls[ self.__host.phone.raw_number]['Channel-Call-UUID']) self.__prompt_engine.play_prompt( self.__prompt_engine.CALL_BACK_NOTIFICATION, self.__call_handler, call_info['Channel-Call-UUID']) time.sleep(5) self.__call_handler.hangup(call_info['Channel-Call-UUID']) self.program.log_program_activity( "Call from community caller {0} was queued".format( call_info['Caller-Destination-Number'])) elif self.__phone_status == PhoneStatus.REJECTING: # Hangup the call self.__call_handler.hangup(call_info['Channel-Call-UUID']) self.__call_handler.bridge_incoming_call( call_info['Channel-Call-UUID'], "{0}_temp{1}".format(self.program.id, self.program.radio_station.id)) self.__prompt_engine.play_prompt( self.__prompt_engine.CALL_BACK_NOTIFICATION, self.__call_handler, call_info['Channel-Call-UUID']) self.__call_handler.register_for_call_hangup( self, call_info['Caller-Destination-Number']) self.program.log_program_activity( "Call from community caller {0} was rejected".format( call_info['Caller-Destination-Number'])) elif self.__phone_status == PhoneStatus.WAKE: # Hangup the call if len(self.__community_call_UUIDs) == 0: self.__call_handler.bridge_incoming_call( call_info['Channel-Call-UUID'], "{0}_{1}".format(self.program.id, self.program.radio_station.id)) self.__call_handler.register_for_call_hangup( self, call_info['Caller-Destination-Number']) self.__community_call_UUIDs[ call_info['Caller-Destination-Number']] = call_info[ 'Channel-Call-UUID'] self.program.log_program_activity( "Call from community caller {0} was auto-answered".format( call_info['Caller-Destination-Number'])) self.__prompt_engine.play_prompt( self.__prompt_engine.AWAIT_HOST_CONNECTION, self.__call_handler, call_info['Channel-Call-UUID']) self.request_host_call(True) #self.__call_handler.speak('Please wait while we connect you to the host', call_info['Channel-Call-UUID']) def __schedule_host_callback(self): time_delta = timedelta(seconds=300) # one minutes now = datetime.now() callback_time = now + time_delta self.__scheduler.add_date_job(getattr(self, 'request_host_call'), callback_time) def __schedule_warning(self): time_delta = timedelta(seconds=self.__warning_time) now = datetime.utcnow() warning_time = now + time_delta self.__scheduler.add_date_job(getattr(self, 'warn_number'), warning_time) def __schedule_hangup(self): time_delta = timedelta(seconds=self.duration) now = datetime.utcnow() hangup_time = now + time_delta self.__scheduler.add_date_job(getattr(self, 'hangup_call'), hangup_time) def __deregister_listeners(self): for available_call in self.__available_calls: self.__call_handler.deregister_for_call_hangup(available_call) self.__call_handler.deregister_for_incoming_calls(self) self.__call_handler.deregister_for_incoming_dtmf( str(self.__host.phone.raw_number))
# Using APSceduler for scheduling python scheduler jobs # Triggering a windows bat file #!/usr/bin/python import os from apscheduler.scheduler import Scheduler # Start the scheduler sched = Scheduler() sched.start() print("hello") def job_function(): os.system('D:\SimpleBatchFile.bat') # Schedule a backup to run once from Monday to Friday at 4:00 (pm) sched.add_cron_job(job_function, day_of_week='mon-fri', hour=16, minute=0)
from datetime import datetime import signal import daemon import lockfile from apscheduler.scheduler import Scheduler def job_function(): print "Hello World" def main(): signal.pause() if __name__ == '__main__': sched = Scheduler() sched.daemonic = True sched.start() sched.add_interval_job(job_function, minutes=1) context = daemon.DaemonContext( working_directory='/data', umask=0o002, pidfile=lockfile.FileLock('/tmp/wikipedia_pagecount.pid'), ) context.signal_map = { signal.SIGTERM: 'terminate', signal.SIGHUP: 'terminate', signal.SIGUSR1: 'terminate' }
# # Imports from apscheduler.scheduler import Scheduler import webbrowser import requests import time import json import os # Quote Config hour = 9 minute = 20 # Start the scheduler sched = Scheduler() sched.start() # Update Index def updateIndex(quote, author): template = open("./template/template.html", "r") index = open("./template/index.html", "w") code = template.read() code = code.replace("{quote}", quote) code = code.replace("{author}", author) index.write(code) # Update Style def updateStyle(background): template = open("./template/assets/css/template.css", "r")
#from datetime import datetime #from threading import Timer #from crontab import CronTab from apscheduler.scheduler import Scheduler import logging from random import choice import serial logging.basicConfig() #-------------------- #---Variables-------- #-------------------- #setup a scheduler object sched = Scheduler() sched.start() #Set up a serial object that connects to whichever port #the arduino is on ACM0 or ACM1; most likely ACM0 device = "/dev/ttyACM0" baud = 9600 ser = serial.Serial(device, baud) #Set Up API account access for @Nellysfood consumer_key = 'DbAGiakC3vg040FJX8A7A' consumer_secret = 'nAFnbwGi6gNb6MRUrqDamMxLSCW1A7OCF4FiepUQIWw' access_token = '1646642456-zECt0bTkcUYQ3z5FFAjeYQbgmKLBGOX66PhiWsP' access_token_secret = 'TxMQD7UO3miZTW4FNjcUJ77vHyVHXMraOL9n4Hx3MM' #Initialize a twitter API instance.