def __run(self, input_path, output_path): self.init = PCB("init", 0) scheduler() if input_path is None: while (True): print("> ", end="") command_line = input() command = command_line.split() self.__process_command(command) else: output_list = [] with open(input_path, mode="r") as in_file: line = ["init"] for command_line in in_file: if command_line.strip() == '': to_append = " ".join(line) if to_append.strip() != '': output_list.append(to_append) line = [] else: result = self.__process_command(command_line.split()) line.append(result) if len(line): output_list.append(" ".join(line)) output_str = "\n".join(output_list) if output_path is not None: with open(output_path, mode="w") as out_file: out_file.write(output_str) else: print(output_str)
def menu_select(available_dates, apps): """The menu_select function takes user input for the interface menu. While loop repeats if a user inputs anything besides a menu integer. """ while True: choice = input("\nType the number of your choice and press 'Enter': ") # If user chooses list appnts, call show_apps method and exit loop. if choice == '1': os.system('clear') apps.print_apps() input("\nPress 'Enter' to continue.") return True # If user chooses schedule, call schedule function and exit loop. elif choice == '2': os.system('clear') scheduler.scheduler(available_dates, apps) input("\nPress 'Enter' to continue.") return True # If user chooses to exit, exit loop and return False. elif choice == '3': print("\nThank you for being a proud employee of The Hair Hut!") return False # If user input is invalid, display message and repeat loop. else: print("\nInvalid input. Input must be '1', '2', or '3'.")
def test_connect(): # need visibility of the global thread object global thread print('Flask Client connected') #Start the generator threads only if the thread has not been started before. if not thread.isAlive(): scheduler()
def test_scheduler(self): s = scheduler.scheduler() assert (s == '[[1, 3], [2]]') s = scheduler.scheduler(start='2019-11-11 09:00:00') assert (s == '[[2]]') s = scheduler.scheduler(finish='2019-11-11 8:00:00') assert (s == '[[1, 3]]') s = scheduler.scheduler(max_window='4 horas') assert (s == '[[1], [2]]')
def post(self, **params): module = self.get_argument('module', 'missing') if module == 'missing': self.clear() self.set_status(404) self.finish("<html><body>Missing function call</body></html>") return else: Log.Debug('Recieved a post call for module: ' + module) if module == 'logs': self = logs().reqprocessPost(self) elif module == 'settings': self = settings().reqprocessPost(self) elif module == 'pms': self = pms().reqprocessPost(self) elif module == 'findMedia': self = findMedia().reqprocessPost(self) elif module == 'wt': self = wt().reqprocessPost(self) elif module == 'scheduler': self = scheduler().reqprocessPost(self) elif module == 'jsonExporter': self = jsonExporter().reqprocessPost(self) else: self.clear() self.set_status(412) self.finish('Unknown module call') return
def kaikki(hours, args, room_id, db): # Name for event must be specified event_name = args.strip() if len(event_name) == 0 or 24 < hours < 1: return "" event_doc = db.objects.find_one({ "room_id": room_id, "event_name": event_name }) if event_doc is not None: times, days = get_relative_times(event_doc["times"]) result_times = scheduler.scheduler(times, hours, get_all=True) if result_times is not None: """ Maanantai 11-12, 12-13, 15-16 Torstai 11-12 Sunnuntai 12-13, 15-16 result_times = [ ((alku1, loppu1), lkm_väli), ((alku2, loppu2), lkm_väli) ... ] """ result_times = sorted(result_times, key=lambda x: x[0][0]) result_times = groupby(result_times, key=lambda x: x[0][0].day) result_times = [(k, list(g)) for k, g in result_times] """ result_times = [ (pvä1, [ ((alku1, loppu1), lkm_väli), ((alku2, loppu2), lkm_väli) ]), (pvä2, [ ((alku3, loppu3), lkm_väli), ((alku4, loppu4), lkm_väli), ((alku5, loppu5), lkm_väli) ]) ] """ # Get number of participants here for printing n = result_times[0][1][0][1] spanstring = "" for day, timesofday in result_times: spanstring += "{}: ".format(days[day]) for time in timesofday: spanstring += "{}-{}; ".format(time[0][0].hour, time[0][1].hour + 1) spanstring += "\n" return "'{}': Kaikki sopivat ajat osallistujamäärällä {}/{}:\n{}" \ .format(event_name, n, len(times), spanstring) return f"'{event_name}': Ei löydy yhteisiä aikoja" return f"'{event_name}': Tapahtumaa ei löydy huoneesta"
def buildschedule(self): sets = set() sets.add(0) for i in self.action: sets.add(i.actiontime) self.schedule = scheduler(sets)
def demo_create(filename='ovs.xml'): #测试使用,正式版删除 # ip_start={ # "start":"10.0.0.0" # } mongo=mongodb.mongo_opreate() mongo.save_tpl_dic(ip_start,"ip_start") #建立对象 test=ip_distribution.ip_distribution() example=scheduler.scheduler() #获取列表 list_ovs,list_relation=resolve_xml_ovs.get_xml_ovs(filename) list_host=resolve_xml_ovs.get_xml_host_conf() list_ovs_new=test.distribution_ovs(list_ovs) operation,list_ovs_new_new,ovs_link=example.docker_scheduler(list_ovs_new,list_host,list_relation) #构建任务字典 task_list={ "id":srand(), "ovs_link":list_relation, "ovs_tube_link":ovs_link, "ovs_list":list_ovs_new_new, "host_list":list_host, "operate":operation, "state":"" } return task_list
def demo_create(filename='ovs.xml'): #测试使用,正式版删除 # ip_start={ # "start":"10.0.0.0" # } mongo = mongodb.mongo_opreate() mongo.save_tpl_dic(ip_start, "ip_start") #建立对象 test = ip_distribution.ip_distribution() example = scheduler.scheduler() #获取列表 list_ovs, list_relation = resolve_xml_ovs.get_xml_ovs(filename) list_host = resolve_xml_ovs.get_xml_host_conf() list_ovs_new = test.distribution_ovs(list_ovs) operation, list_ovs_new_new, ovs_link = example.docker_scheduler( list_ovs_new, list_host, list_relation) #构建任务字典 task_list = { "id": srand(), "ovs_link": list_relation, "ovs_tube_link": ovs_link, "ovs_list": list_ovs_new_new, "host_list": list_host, "operate": operation, "state": "" } return task_list
def tulokset(hours, args, room_id, db): # Name for event must be specified event_name = args.strip() if len(event_name) == 0: return "" event_doc = db.objects.find_one({ "room_id": room_id, "event_name": event_name }) if event_doc is not None: times, days = get_relative_times(event_doc["times"]) result_time = scheduler.scheduler(times, hours) if result_time is not None: return "'{}': {} {}-{}, osallistujia {}/{}" \ .format(event_name, days[result_time[0][0].day], result_time[0][0].hour, result_time[0][1].hour+1, result_time[1], len(times)) return f"'{event_name}': Ei löydy yhteistä aikaa" return f"'{event_name}': Tapahtumaa ei löydy huoneesta"
def initServer(self): # Dictionary with experiment.name as keys and # script_class_parameters instances are the values. self.script_parameters = {} # Instance of a complicated object self.scheduler = scheduler(ScriptSignalsServer) self.load_scripts()
def initServer(self): # Dictionary with experiment.name as keys and # script_class_parameters instances are the values. self.script_parameters = {} # Instance of a complicated object self.scheduler = scheduler(Signals) self.load_scripts()
def initialize(): if request.method == 'POST': google_key = request.files['google_key'] google_service_account = request.form['google_service_account'] google_project_id = request.form['google_project_id'] azure_account_name = request.form['azure_account_name'] azure_account_key = request.form['azure_account_key'] s3_access_key_id = request.form['s3_access_key_id'] s3_secret_access_key = request.form['s3_secret_access_key'] global username username = request.form['username'] decrypt_password = request.form['decrypt_password'] with open(basedir + '/boto', 'w') as boto_file: boto_file.write( '[Credentials]\ngs_service_key_file = google_key.p12\ngs_service_client_id = ' + google_service_account + '\n[Boto]\nhttps_validate_certificates = True\n[GoogleCompute]\n[GSUtil]\ncontent_language = en\ndefault_project_id = ' + google_project_id + '\n[OAuth2]') boto_file.close() global custom_api import custom_api global scheduler from scheduler import scheduler scheduler = scheduler(num_workers=5) backup_key_path = backup_google_key_folder + '/google_key.p12' google_key.save(backup_key_path) google_info, azure_info, aws_info = custom_api.initialize( google_project_id, azure_account_name, azure_account_key, s3_access_key_id, s3_secret_access_key) if username == '': user_info = 'Failed to Initialize User!' else: if decrypt_password == '': if (os.path.isfile( os.path.join(basedir, key_file_folder) + username + '.pem')): user_info = 'Successfully Initialized User!' else: user_info = 'Failed to Initalize User! Please Provide Password!' else: if (os.path.isfile( os.path.join(basedir, key_file_folder) + username + '.pem')): user_info = 'User Existed!' else: # RSA public/private key generation custom_api.rsa_key(decrypt_password, username) user_info = 'Successfully Initialized User!' flag = 1 return render_template('initialize.html', status=flag, google=google_info, azure=azure_info, aws=aws_info, user=user_info) else: return render_template('initialize.html')
def __init__(self, config): self._t1 = time.time() self._config = config self._listeners = {} self._application_exit_request = False self._context = zmq.Context() self._player = player(self._context, config) self._scheduler = scheduler(config=config) self._acquirer = acquirer() self._player.set_scheduler(self._scheduler)
def _execute_command(self, command: list): commands = {"init": "Shell.init", "cr": "Shell.create_process", "de": "Shell.destroy_process", "req": "Shell.request_resource", "rel": "Shell.release_resource", "to": "Shell.timeout", "ps": "Shell.process_status", "rls": "Shell.ready_list_status"} cmd = commands[command[0]] param_string = "" if (len(command[1:])): param_string = ", '" + "', '".join(command[1:]) + "'" exec(cmd + "(self" + param_string + ")") if(command[0] in ["init", "cr", "de", "req", "rel", "to"]): scheduler()
def create_class_objects(self,tel_num=1): # create a scheduler for the sim self.scheduler = scheduler.scheduler('scheduler.ini') # get the weather stats self.get_weather_probs('dailyprob.txt') # create the telescopes self.telescopes = [] for ind in range(tel_num): self.telescopes.append(telescope.telescope('telescope.ini',ind+1))
def __init__(self, *args, **kwargs): self.scheduler = scheduler() self.__running = False # Intentionally don't want to start!! self.__dont_start = True self.__retry_count = 0 self.__start_max_retries = 5 self.__retry_timeout = 5 #seconds self.__data_transfer_job = None self.__data_transfer_timeout = 15 #seconds
def initServer(self): """Load all of the paramters from the registry.""" self.listeners = set() self.parameters = {} yield self.load_parameters() self.sequences = {} # dict mapping sequence names to modules self.datasets = {} # dictionary mapping sequences to dataset objects self.scheduler = scheduler(Signals, self) self.load_sequences()
def deal_data(self, connbuf, addr): print() print("Got a connection from ", addr) absolute_path = '/var/www/socialmails/schedule_server/' connbuf.put_utf8('Hi, Welcome to the server!') smtp_data = connbuf.get_utf8() db_data = connbuf.get_utf8() eml_type = connbuf.get_utf8() eml_name = absolute_path + 'eml/' + connbuf.get_utf8().split('/')[-1] user_group = connbuf.get_utf8() mail_excel = absolute_path + 'excel/' + connbuf.get_utf8().split( '/')[-1] annex = absolute_path + 'annex/' + connbuf.get_utf8().split('/')[-1] url = connbuf.get_utf8() datetime = connbuf.get_utf8() absolute_path = '/var/www/socialmails/schedule_server/' for file_name in [eml_name, mail_excel, annex]: file_size = int(connbuf.get_utf8()) print('file size: ', file_size) with open(file_name, 'wb') as f: remaining = file_size while remaining: chunk_size = 4096 if remaining >= 4096 else remaining chunk = connbuf.get_bytes(chunk_size) if not chunk: break f.write(chunk) remaining -= len(chunk) if remaining: print(file_name, ' incomplete. Missing', remaining, 'bytes.') else: print(file_name, ' received successfully.') print('All data ({0}, {1}, {2})'.format(smtp_data, db_data, url)) print() scheduler(datetime, [ smtp_data, db_data, eml_type, eml_name, user_group, mail_excel, annex, url ])
def my_world_scheduler(resources_filename, initial_state_filename, output_filename, num_turns, depth_bound, frontier_max_size): choice_num = prompt_user_choice() # Get user's game setting choice df_resources = get_data_from_file(resources_filename) # Load resources data from data frame df_countries = get_data_from_file(initial_state_filename) # Load country data frame world_matrix = create_matrix(df_countries, df_resources) # Get the two data frames into a matrix world_object = generate_world(world_matrix, df_resources, df_countries) # Create the world object with country objects and weights valid_transforms, valid_transfers = initialize_resources_list( choice_num) # Set of resources which will be valid in this mode countries = world_object.get_countries() world_object.set_user_setting(choice_num) # set the world object into user's desired mode country_name, population, timber, metallic_elements, disaster_prob = user_resource_input(choice_num) cur_world_object = world_object # Updates user country according to user preferences update_user_country(cur_world_object, country_name, population, timber, metallic_elements, disaster_prob) dict_moves = {} init_state_quality_dict = {} for country in countries: init_state_quality_dict[country] = sq.state_quality(country, cur_world_object) for x in range(num_turns): print("\n----- Turn # " + str(x + 1) + " -----\n") for country in countries: move_name = "Turn #" + str(x + 1) + ": " + country + ": " new_world = sd.scheduler(cur_world_object, country, 1, depth_bound , frontier_max_size, valid_transforms, valid_transfers) cur_world_object = new_world if choice_num is 4: # Run disaster mode if user selects option 4 cur_world_object.disaster(country) # Whether disaster was called or not (necessary for path) moves_as_list = cur_world_object.get_path() cur_move = moves_as_list[len(moves_as_list) - 1] dict_moves[move_name] = cur_move print(move_name + str(cur_move)) cur_world_object.turn_resources() # Adds resources after every turn (I figured after made sense bc of 1st turn) print_game_output_to_file(output_filename, dict_moves) final_state_quality_dict = {} for country in countries: final_state_quality_dict[country] = sq.state_quality(country, cur_world_object) state_quality_diff = {} for country in countries: state_quality_diff[country] = final_state_quality_dict[country] - init_state_quality_dict[country] print("\n\nHere are each country's statequality improvements. Find out where you rank.") for x in state_quality_diff: print("\t" + str(x) + " achieved the following improvement:" + '{0:>15.3g}'.format(state_quality_diff[x])) print("\n\nScheduling complete -- Check " + output_filename + " file for results")
def create_class_objects(self,tel_num=1): # create a scheduler for the sim self.scheduler = scheduler.scheduler('scheduler.ini') # get the weather stats self.get_weather_probs('dailyprob.txt') # create the telescopes self.telescopes = [] for ind in range(tel_num): self.telescopes.append(telescope.telescope('telescope.ini',ind+1)) self.instruments = [] for ind in range(tel_num): self.instruments.append(telescope.instrument('instrument.ini',ind+1))
def produce(parents): if len(parents) == 0: print('error') parents = sorted(parents, key = lambda x: scheduler(toList(x), CAPACITY)[0]) maxLengthCross = math.floor(len(parents) * c_ratio) offspring = [] # crossover for p in parents: offspring.extend(crossover(list(parents[0]), list(p), random.randint(1, maxLengthCross))) # mutation for o in offspring: mutation(o) offspring = sorted(offspring, key = lambda x: scheduler(toList(x), CAPACITY)[0]) offspring = offspring[:1] return offspring
def main(): mainLogger = logger.logger("main") mainLogger.log.info("Starting main") mainInterfaces = interfaces.interfaces() openInterfaces(mainInterfaces) mainDataManager = dataManager.dataManager(interfaces=mainInterfaces) ######## GENERATE FAKE DATA DONT FORGET TO REMOVE THIS ##################### # mainDataManager.genFakeData() ############################################################################ axLogPath = "/logs/axlisten.log" ground = groundComms.groundComms(axLogPath=axLogPath, interfaces=mainInterfaces, dataManager=mainDataManager) mainInterfaces.gpio.setPinMode(pin=18, mode=mainInterfaces.gpio.OUTPUT) # Status LED # Schedule tasks mainScheduler = scheduler.scheduler() mainScheduler.schedule(callback=mainDataManager.setTimeSync, frequency=20) mainScheduler.schedule(callback=mainDataManager.log, frequency=3) mainScheduler.schedule(callback=ground.streamTelemetry, frequency=10) mainScheduler.schedule(callback=mainInterfaces.habip_osd.cycle, frequency=20) # Set OSD header because fun header = "{} RIT TEAM HABIP {}".format(mainInterfaces.osd232.symbol["satellite"], mainInterfaces.osd232.symbol["heart"]) mainInterfaces.habip_osd.header = header run = True while run: mainInterfaces.watchdog.pet() # Pet the watchdog mainInterfaces.gpio.toggleOutput(18) # Status LED ground.update() ground.executeCommands(withDelay=100) mainDataManager.update() mainInterfaces.daqcs.update() mainScheduler.update() mainInterfaces.habip_osd.update_all() # This takes about a second to process # print mainInterfaces.habip_osd.osd232.preview() # for name, board in mainInterfaces.boards.iteritems(): # print "Data for board: {}".format(name) # board.printAllData() mainLogger.log.info("main loop terminating")
def createDownTimeTemplate(): sch = scheduler.scheduler() Down_Time = sch.newEventTemplate(event_name = 'Down Time', event_type = 'Free Time', calendar = calhelp.getCalendarId(sch.service,'Health'), duration = 60, days_till_expire = 0, urgency = 1, importance = 1, reschedulability = -1, #-1 is a special reschedulability class meaning fine to drop (with no consequences) extensibility = 30, shortenability = 60) sch.saveEventTemplate(Down_Time,'Down_Time')
def hello(): form = ReusableForm(request.form) # print(form.errors) if request.method == 'POST': item = request.form['item'] min_price = request.form['min_price'] max_price = request.form['max_price'] # send_email = request.form['sender_email'] # receive_email = request.form['receiver_email'] # password = request.form['sender_password'] chat_id = request.form['chat_id'] period = request.form['period'] interval = request.form['interval'] if form.validate(): sch.scheduler(item, min_price, max_price, int(chat_id), int(period), int(interval)) flash('Done ') else: flash('Error: All Fields are Required') return render_template('index.html', form=form)
def createStudyTemplates(): sch =scheduler.scheduler() ECE_240 = sch.newEventTemplate(event_name = 'ECE 240 Study', event_type = 'Basic Study', calendar = calhelp.getCalendarId(sch.service,'Study'), duration = 120, days_till_expire = 0, urgency = 5, importance = 4, reschedulability = 1, extensibility = 30, shortenability = 0) ECE_250 = sch.newEventTemplate(event_name = 'ECE 250 Study', event_type = 'Basic Study', calendar = calhelp.getCalendarId(sch.service,'Study'), duration = 60, days_till_expire = 0, urgency = 5, importance = 4, reschedulability = 1, extensibility = 30, shortenability = 0) ECE_222 = sch.newEventTemplate(event_name = 'ECE 222 Study', event_type = 'Basic Study', calendar = calhelp.getCalendarId(sch.service,'Study'), duration = 60, days_till_expire = 0, urgency = 5, importance = 4, reschedulability = 1, extensibility = 30, shortenability = 0) ECE_290 = sch.newEventTemplate(event_name = 'ECE 290 Study', event_type = 'Basic Study', calendar = calhelp.getCalendarId(sch.service,'Study'), duration = 60, days_till_expire = 0, urgency = 5, importance = 4, reschedulability = 1, extensibility = 30, shortenability = 0) sch.saveEventTemplate(ECE_240,'ECE_240_Study') sch.saveEventTemplate(ECE_250,'ECE_250_Study') sch.saveEventTemplate(ECE_222,'ECE_222_Study') sch.saveEventTemplate(ECE_290,'ECE_290_Study')
def get(self, **params): module = self.get_argument('module', 'missing') if module == 'missing': self.clear() self.set_status(404) self.finish('Missing function call') return else: Log.Debug('Recieved a get call for module: ' + module) #TODO ''' Attempt to create a dynamic import, but so far, it sadly breaks access to the PMS API :-( import sys sys.path.append(os.path.join(Core.app_support_path, 'Plug-ins', NAME + '.bundle', 'Contents', 'Code')) mod = import_module(module) modClass = getattr(mod, module)() print 'GED1', dir(modClass) callFunction = getattr(modClass, 'reqprocess') self = modClass().reqprocess(self) ''' if module == 'git': self = git().reqprocess(self) elif module == 'logs': self = logs().reqprocess(self) elif module == 'pms': self = pms().reqprocess(self) elif module == 'settings': self = settings().reqprocess(self) elif module == 'findMedia': self = findMedia().reqprocess(self) elif module == 'language': self = language().reqprocess(self) elif module == 'plex2csv': self = plex2csv().reqprocess(self) elif module == 'wt': self = wt().reqprocess(self) elif module == 'scheduler': print 'Ged WebSrv Scheduler' self = scheduler().reqprocess(self) else: self.clear() self.set_status(412) self.finish('Unknown module call') return
def validate_modules(self, modules): """ Validate each of the modules. Invalid modules will be removed so that valid ones can still function. Defaults for missing attributes are also added. """ self.modules = {} for i, info in modules.iteritems(): log.info("Checking module: %s" % i) valid = True if not info.has_key('method'): log.error("ERROR: Module (%s) Missing attribute: 'method'" % i) valid = False elif not type(info['method']).__name__ == 'classobj': log.error( "ERROR: Module's 'method' attribute is not a classobj: %s" % info['method']) valid = False if info.has_key('hosts'): if not info['hosts']: info['hosts'] = self.DEFAULTS['hosts'] if info.has_key('interval'): if type(info['interval']) is int: info['interval'] = "%ss" % info['interval'] if not info['interval']: info['interval'] = self.DEFAULTS['interval'] if info.has_key('start'): if not info['start']: info['start'] = self.DEFAULTS['start'] if info.has_key('days'): if not info['days']: info['days'] = self.DEFAULTS['days'] for attr in ['hosts', 'interval', 'start', 'days']: if not info.has_key(attr): info[attr] = self.DEFAULTS[attr] if valid: if self.hostname in info['hosts']: # add the next_marker attribute info['next_marker'] = None # attach a scheduler info['scheduler'] = scheduler(interval=info['interval'], start=info['start'], days=info['days']) self.modules[i] = info
def test_scheduler(): if os.path.isdir('./lists'): print('remove playlist folder') shutil.rmtree('./lists') with scheduler(config=CONFIG) as s: lists = s.get_smartlists() print(lists) assert s.get_active_smartlist() == 'unspecified' s.add_path(path=os.path.dirname(__file__)) s.activate_smartlist('party') _some_track = ('/root', 'some/path', 'file.mp3') # upvote s.add_tag(listener='frans', track=('/root', 'some/path', 'file.mp3'), pos=123, details={'tag_name': 'upvote'}) #ban s.add_tag(listener='frans', track=_some_track, pos=123, details={ 'tag_name': 'ban', 'subject': 'some/file_substring' }) print(s.present_listeners()) s.add_present_listener('frans') s.add_present_listener('julia') print(s.present_listeners()) s.remove_present_listener('frans')
def command_handler(): #eventually turn this into a command->fn dict command = "" while "quit" not in command or "exit" not in command or "nothing" not in command or "go" not in command: command = str(input("What do you want to do? \n")).lower() if "go" in command and "to" in command or "goto" in command or "show" in command and "me" in command: if True: webnav.navigate_web(command) print("Launching web.") else: print("You don't currently have web access.") elif "headsdownfor" in command or "hdfor" in command: print(scheduler.scheduler(command)) elif "blocktime" in command or "time" in command: print(scheduler.wake_update()) elif "unblock" in command: print(scheduler.unblock()) elif "callme" in command or "call me" in command: print(greeting.nickname(command)) elif "lyrics" in command and "by" in command: print(music.query_handler(command)) elif "run" in command: print(terminal.run_bash(command[command.index("run")+3:])) elif "plus one" in command or "+1" in command or "+ 1" in command or "plus 1" in command: print(motiv.plus_one()) elif "get score" in command or "getscore" in command: print(motiv.get_score(False)) elif "reset" in command: print(motiv.reset()) elif "quit" in command or "exit" in command or "nothing" in command or "go" in command: break else: print("Invalid command: " + command) if validity_checker(command): history.add_to_history(command) return "Have a nice day! (=^..^=)"
def demo_create(): #建立对象 test=ip_distribution.ip_distribution() example=scheduler.scheduler() #获取列表 list_ovs,list_relation=resolve_xml_ovs.get_xml_ovs() list_host=resolve_xml_ovs.get_xml_host_conf() list_ovs_new=test.distribution_ovs(list_ovs) operation,list_ovs_new_new,ovs_link=example.docker_scheduler(list_ovs_new,list_host,list_relation) #构建任务字典 task_list={ "id":srand(), "ovs_link":list_relation, "ovs_tube_link":ovs_link, "ovs_list":list_ovs_new_new, "host_list":list_host, "operate":operation, "state":"" } return task_list
#! /usr/bin/python from scheduler import scheduler from subprocess import call # Run Terminal Command def executePythonScript(script=''): if script: call(['python', '/Users/me/' + script]) # run if __name__ == '__main__': # Create a new scheduler scheduler = scheduler() # Define our scheduler commands: scheduler.at('03:00').do(executePythonScript, script='nightly_backup.py') scheduler.at('04:00').do(executePythonScript, script='master_duplicate.py') scheduler.every(5).minutes().do(executePythonScript, script='dropbox_cleanup.py') # eof
def initServer(self): self.script_parameters = {} self.scheduler = scheduler(Signals) self.load_scripts()
# inspect is needed to get the function name import inspect # this is a common function which is scheduled # at many times using many different scheduler # functions like at(), every(), after() and cron(). def func(args): fname = inspect.stack()[0][3] #function name print '%s : %s : current time "%s"' % \ (fname, args, datetime.now()) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # create an instance of the scheduler sched = scheduler() # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Scheduler.at() # # input: # func : name of the function to be called # date : date and time to be called # args : arguments to the function 'func' # # an at() job executes at 10 seconds from now j1_time = datetime.now() + timedelta(seconds=10) at_j1 = sched.at(func, j1_time, args=["AT +10s"])
parser.add_argument('--jobId', metavar='<Local jobId>', required = True, help='The ID of the job whose information is required') parser.add_argument('--to', metavar='<clusterName>', help='The name of the cluster on which the job has to be submitted') # Extract the arguments obtained from the user for the delete command args = parser.parse_args() jobId = args.jobId if args.to is not None: clusterName = args.to else: clusterName = None # The user will provide the data in the JSON format. # Call the function from_json to extract the contents from JSON file Config_ = Config() resourceObj, subScheduler = Config_.from_json("config.json", clusterName) Schduler_ = scheduler() if(subScheduler == "PBS"): subScheduler = PBS(Schduler_) elif(subScheduler == "Condor"): subScheduler = Condor(Schduler_) # Reads the information of the particular job object. This is # done based on the jobId provided by the user inp_file = 'pickle_' + jobId with open(inp_file, 'rb') as f: Job_ = pickle.load(f) subScheduler.Query(args, Job_, resourceObj)
'''import symbolic_object from symbolic_object_list import symbolic_object_list import compute import scheduler import cas_manager_interface''' #import server import cas_manager_interface import scheduler #Call the various initializers #symbolic_object_list.initialize() eatComputations = scheduler.scheduler() cas_manager_interface.initialize(eatComputations) #while True: try: eatComputations.start() except: print("Exception detected in the scheduler. Researting it, all computation requests will be lost.") #Warning: Exceptions in the thread do not reach here. Do something else to resolve this issue #eatComputations.pause() def computationScheduler(): return eatComputations
from flask import Flask, render_template, request, redirect, url_for from flask.ext.sqlalchemy import SQLAlchemy from logging import Formatter, FileHandler from database import db_session, init_db from models import User, Job from forms import * from scheduler import scheduler, load_jobs import logging app = Flask(__name__) app.config.from_object('config') init_db() scheduler() # Automatically tear down SQLAlchemy. @app.teardown_request def shutdown_session(exception=None): db_session.remove() # Login required decorator. def login_required(test): @wraps(test) def wrap(*args, **kwargs): if 'logged_in' in session: return test(*args, **kwargs) else:
__author__ = 'amaliujia' from scheduler import scheduler from crawler import crawler def add_crawler(crawlers, scheduler): crawlers.append(crawler(scheduler)) if __name__=="__main__": s = scheduler() crawlers = [] add_crawler(crawlers, s) add_crawler(crawlers, s) add_crawler(crawlers, s) add_crawler(crawlers, s) add_crawler(crawlers, s) add_crawler(crawlers, s) s.add_task("http://news.ifeng.com/", "feng_news", "list") for crawler in crawlers: crawler.start()
from scheduler import scheduler if __name__ == "__main__": scheduler()
start_time_ga = time.time() sum_asap = 0.0 sum_ga = 0.0 for i in range(ITERATION_TIMES): p_list = getPatients(p_num, RELEASE_DAY_RANGE, DUE_DAY_RANGE, TREATMENT_DAY_RANGE, MAX_INTERUPT) start_time_asap = time.time() asap_list, asap_sequence = ASAPSort(p_list) cost_asap = time.time() - start_time_asap ga_list, ga_sequence = GASort(p_list, MAX_ITERATION, MUTATION_RATE, CROSSOVER_RATE, POPULATION) # print(asap_sequence, ga_sequence) asap_tardiness = scheduler(asap_list, CAPACITY)[0] ga_tardiness = scheduler(ga_list, CAPACITY)[0] sum_asap += asap_tardiness sum_ga += ga_tardiness y_asap.append(sum_asap / ITERATION_TIMES) y_ga.append(sum_ga / ITERATION_TIMES) timecost_asap.append(cost_asap) timecost_ga.append((time.time() - start_time_ga)) print(timecost_asap) print(timecost_ga) # if asap_tardiness[0] != 0:
def run_collectors(self, names): """if you want to override the normal frequency of a collector, provide a list of names to do, and they will be scheduled""" scheduler(names, self.mysql_conn)
import bases import time import global_info import scheduler if __name__=='__main__': wf = global_info.taskgraph('wf') c = scheduler.scheduler('c','localhost') # 1st subgraph w0 = wf.suc_extract('w0') w0info = bases.infodict(w0) w0bytesinfo = c.json_encode(w0info) c.send(w0bytesinfo, 'localhost', 2014) c.sndsock.close()