当前位置: 首页>>代码示例>>Python>>正文


Python Scheduler.start方法代码示例

本文整理汇总了Python中Scheduler.Scheduler.start方法的典型用法代码示例。如果您正苦于以下问题:Python Scheduler.start方法的具体用法?Python Scheduler.start怎么用?Python Scheduler.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Scheduler.Scheduler的用法示例。


在下文中一共展示了Scheduler.start方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from Scheduler import Scheduler [as 别名]
# 或者: from Scheduler.Scheduler import start [as 别名]
class MessageHandler:

    def __init__(self, bot):
        self.math_parser = NumericStringParser()
        self.pprinter = pprint.PrettyPrinter(indent=4)
        self.bot = bot
        self.enable_bot = False
        self.last_msg = long(str(time.time()).split('.')[0])
        self.scheduler = Scheduler()
        self.scheduler.start()

        self.command_dict = dict()
        self.help_dict = dict()
        self.command_admin_permission = dict()
        self.command_enable_permission = dict()

        # add commands as needed
        self.register_command('enable', self.enable_bot_cmd, admin_only=True, enable_independent=True)
        self.register_command('disable', self.disable_bot_cmd, admin_only=True)
        self.register_command('join', self.join_cmd, admin_only=True)
        self.register_command('help', self.help_cmd, help='Display this message')

        self.register_command('math', MathHandler.MathHandler(self.bot, self.math_parser).handle,
                              help='Executes basic mathematics statements')

        google_engine_id = self.bot.config.get('Authentication', 'google_search_engine_id')
        google_auth_token = self.bot.config.get('Authentication', 'google_search_api_token')
        self.register_command('image', ImageSearch.ImageSearch(self.bot, google_auth_token, google_engine_id).handle,
                              help='Finds and displays the requested image from the internet. \n'
                                   'You can specify filetype:gif for animated images.\n'
                                   'Limited to 1 query per second.')
        self.register_command('gif', GifSearch.GifSearch(self.bot, google_auth_token, google_engine_id).handle,
                              help='Finds and displays the requested gif image from the internet. \n'
                              'Limited to 1 query per second.')
        self.register_command('mtg', MagicHandler.MagicTheGatheringHandler(self.bot).handle,
                              help='Finds and displays the requested Magic: The Gathering card.')
        self.register_command('wiki', WikipediaHandler.WikipediaHandler(self.bot).handle,
                              help='Finds and displays the requested wikipedia article, if it exists.')
        self.register_command('netrunner', NetrunnerHandler.NetrunnerHandler(self.bot).handle,
                              help='Finds and displays the requested Android: Netrunner card.')
        self.register_command('remind', self.remindme_cmd,
                              help='Reminds the user after the requested time period.')
        self.register_command('similarartist', SimilarArtist.SimilarArtist(self.bot).handle,
                              help='Displays a similar artist to the listed one.')
        self.register_command('lenny', LennyFaceHandler.LennyFaceHandler(self.bot).handle,
                              help='Finds and displays a random Lenny Face.')
        self.register_command('roll', RollHandler.RollHandler(self.bot).handle,
                              help='Rolls Y X-sided dice with the phrasing !roll YdX')
        self.register_command('translate', TranslateHandler.TranslateHandler(self.bot).handle,
                              help='Translates a phrase from one language to another. \nUse   '
                                     ' phrase|from_language|to_language \n'
                                     'OR phrase|to_language to translate to another language and trust in language auto-detection\n'
                                     'OR just phrase if you want to translate to English and still trust auto-detection. \n')
        wolfram_alpha_api_token = self.bot.config.get('Authentication', 'wolfram_alpha_api_token')
        self.wolfram_alpha_client = WolframAlphaClient(wolfram_alpha_api_token)
        self.register_command('wolfram',
                              WolframBasicQuery.WolframAlphaBasicQueryHandler(self.bot,
                                                                              self.wolfram_alpha_client).handle,
                              help='Queries WolframAlpha!')
        imgur_id = self.bot.config.get('Authentication', 'imgur_client_id')
        imgur_secret = self.bot.config.get('Authentication', 'imgur_client_secret')
        self.imgur_client = ImgurClient(imgur_id, imgur_secret)
        self.register_command('dankify',
                              Dankify.Dankify(self.bot, self.imgur_client).handle,
                              help='Can be used to produce a dankified image! \n'
                                   'Use: !dankify [url]')

        print('Bot started')

    def register_command(self, command_string, message_handler, help=None,
                         admin_only=False, enable_independent=False):
        self.command_dict[command_string] = message_handler

        if not admin_only:
            self.help_dict[command_string] = help

        if admin_only:
            self.command_admin_permission[command_string] = admin_only
        else:
            self.command_admin_permission[command_string] = False

        if enable_independent:
            self.command_enable_permission[command_string] = enable_independent
        else:
            self.command_enable_permission[command_string] = False

    def handle(self, msg):
        time_stamp_str = msg.xml.attrib['ts'].split('.')[0]
        time_stamp = long(time_stamp_str)

        if time_stamp < self.last_msg:
            return None
        elif msg['type'] == 'groupchat':
            # self.last_msg = time_stamp
            message_body = msg['body']
            from_name_full = msg['mucnick']
            split_str = message_body.split(' ')

            if len(split_str[0]) <= len(COMMAND_CHAR) or not split_str[0].startswith(COMMAND_CHAR):
                return None
#.........这里部分代码省略.........
开发者ID:JeffBorwey,项目名称:HypeBot,代码行数:103,代码来源:MessageHandler.py

示例2: len

# 需要导入模块: from Scheduler import Scheduler [as 别名]
# 或者: from Scheduler.Scheduler import start [as 别名]
	# sample id
	if len(sys.argv) < 2:
		sys.exit(1)

	userID 		= sys.argv[1]
	userPlace 	= sys.argv[2]

	Log(userID)

	Log.debug("=============================================")
	Log.debug("================= Start Bot =================")
	Log.debug("=============================================")

	try:
		schedulerForBot = Scheduler(userID, userPlace)
		if schedulerForBot == None:
			raise Exception

		schedulerForBot.start()
	except Exception as e:
		Log.error("Fail to operate bot")
		
		Log.debug("=========================================================")
		Log.debug("================= Abnormally Finish Bot =================")
		Log.debug("=========================================================")
		sys.exit(1)

	Log.debug("==============================================")
	Log.debug("================= Finish Bot =================")
	Log.debug("==============================================")	
开发者ID:timewizhan,项目名称:MSProject,代码行数:32,代码来源:Bot.py

示例3: __init__

# 需要导入模块: from Scheduler import Scheduler [as 别名]
# 或者: from Scheduler.Scheduler import start [as 别名]
class Ghoul:
    def __init__(self):
        configStream = file('config.yaml', 'r')
        config = yaml.load(configStream)

        self.libraryDB = psycopg2.connect(host = config['music_database']['host'],
                                     user = config['music_database']['user'],
                                     password = config['music_database']['password'],
                                     database = config['music_database']['database'])
        
        try:
            self.messageDB = psycopg2.connect(host = config['msg_database']['host'],
                                     user = config['msg_database']['user'],
                                     password = config['msg_database']['password'],
                                     database = config['msg_database']['database'])
        
            self.messages = MessageLibrary(self.messageDB)
            self.messages.setStingCategories(config['messages']['sting_categories'])
            PlayItem.Message.basePath = config['file_manager']['message_base_path']
        except TypeError:
            self.messages = None
        
        if config['file_manager']['mode'] == "external":
            self.fm = ExternalFileManager(config['file_manager']['user_id'], 
                             config['file_manager']['password'],
                             config['file_manager']['httpUser'],
                             config['file_manager']['httpPass'])

        elif config['file_manager']['mode'] == 'local':
            self.fm = LocalFileManager(config['file_manager']['music_base_path'])


        self.library = MusicLibrary(self.libraryDB)
        self.library.setAustralianNames(config['music']['aus_names'])
        self.library.setMaxSongLength(config['music']['max_song_length'])
        PlayItem.Song.ausNames = config['music']['aus_names']
        
        self.logger = PlaylistLogger(config['logger']['auth'], config['logger']['baseURL'],config['logger']['showID'])
        
        self.playQueue = Queue(5)
       
        self.scheduler = Scheduler(self.library, self.messages, self.fm, self.playQueue)
        self.scheduler.setDemoQuota(config['scheduler']['quotas']['demo'])
        self.scheduler.setLocalQuota(config['scheduler']['quotas']['local'])
        self.scheduler.setAusQuota(config['scheduler']['quotas']['aus'])
        self.scheduler.setFemaleQuota(config['scheduler']['quotas']['female'])
        self.scheduler.setConsecutiveSongs(config['scheduler']['consecutive_songs']['min'],
                                      config['scheduler']['consecutive_songs']['max'])

        self.scheduler.addListener(self)

        self.player = Player.Player()
        self.playThread = Player.PlayThread(self.player, self.playQueue)
        self.playThread.addListener(self)

        self.paused = False

        self.listeners = list()

    def addListener(self, listener):
        self.listeners.append(listener)


    def play(self):
        if self.paused:
            self.paused = False
            self.player.togglePause()
        else:
            self.logger.startNewPlaylist()
            self.scheduler.start()
            self.playThread.start()

    def pause(self):
        self.paused = True
        self.player.togglePause()

    def getElapsedTime(self):
        return self.player.getElapsedTime()

    def getQueuedItems(self):
        items = list()
        for elem in list(self.playQueue.queue):
            items.append(elem)
        return items


    def itemPlaying(self, item):
        if isinstance(item, PlayItem.Song):
            self.logger.submitSong(item)
        for l in self.listeners:
            l.itemPlaying(item)

    def itemQueued(self, item):
        for l in self.listeners:
            l.itemQueued(item)
开发者ID:ThreeDRadio,项目名称:GraveyardGhoul,代码行数:97,代码来源:Ghoul.py

示例4: ThreadKeeper

# 需要导入模块: from Scheduler import Scheduler [as 别名]
# 或者: from Scheduler.Scheduler import start [as 别名]
class ThreadKeeper(threading.Thread):
    def __init__(self,cycle_length,scheduler_length):
        threading.Thread.__init__(self)
        self.folder = BotConfig.KeeperFolder
        self.folderpath = ""
        self.configfile = BotConfig.KeeperConfigFile
        self.cycle_length=cycle_length
        if self.folder:
            try:
                os.mkdir(self.folder)
            except:
                pass
            self.folderpath = self.folder + "/"
        self.configfile = self.folderpath+self.configfile
        self.chans = BotConfig.Chans
        self.threads = {}
        self.threadcnt = {}
        self.threadfiles = {}
        self.threadstates = {}
        self.threadLock = threading.Lock()
        self.scheduler = Scheduler(scheduler_length)
        self.scheduler.start()
        self.Restore()
    def Restore(self):
        serial = None
        try:
            with open(self.configfile,"rb") as f:
                serial = pickle.load(f)
        except:
            pass
        if not serial:
            return
        for (item,value) in serial.iteritems():
            (self.threadfiles[item],self.threadcnt[item],self.threadstates[item]) = value
            (parser,getter) = self.chans[item[0]]
            try:
                with open(value[0],"rb") as f:
                    p = parser.Thread()
                    x = f.read()
                    if not p.DeserializeXml(x):
                        self.threadstates[item] = "NONE"     
                    else:
                        self.threadstates[item] = "OK"           
                    self.threads[item] = p
            except:
                p = parser.Thread()
                self.threadstates[item] = "NONE"
                self.threads[item] = p 
            self.scheduler.AddTask(item,getter,freq=1)

    def GetPath(self,chan,board,thr):
        try:
            os.mkdir(self.folderpath+chan)
        except:
            pass
        try:
            os.mkdir(self.folderpath+chan+"/"+board)
        except:
            pass
        return self.folderpath+chan+"/"+board+"/"+thr
    def AddThread(self,thread,freq=1):
        (chan,board,thr) = thread
        if not (chan in self.chans):
            return False
        tpath = self.GetPath(chan,board,thr)
        with self.threadLock:
            if thread in self.threads:
                self.threadcnt[thread] = self.threadcnt[thread] + 1
            else:
                self.threadcnt[thread] = 1
                self.threadfiles[thread] = tpath 
                (parser,getter) = self.chans[chan]
                self.threads[thread] = parser.Thread()
                self.threadstates[thread] = "NONE"
                self.scheduler.AddTask(thread,getter,freq=1)
            self.Serialize()
        return True
    def Serialize(self):
        with open(self.configfile,"wb") as f:
                serial = {}
                for item in self.threads.keys():
                    serial[item] = (self.threadfiles[item],self.threadcnt[item],self.threadstates[item])
                pickle.dump(serial,f)
    def RemoveThread(self,thread):
        with self.threadLock:
            if thread in self.threads:
                if self.threadcnt[thread] == 1:
                    del self.threadcnt[thread]
                    del self.threadfiles[thread]
                    del self.threads[thread]
                    del self.threadstates[thread]
                    self.scheduler.RemoveTask(thread)
                else:
                    self.threadcnt[thread] = self.threadcnt[thread] - 1
                self.Serialize()

    def GetPosts(self,thread,afternumber=0):
        with self.threadLock:
            state = self.threadstates[thread]
            if afternumber==0:
#.........这里部分代码省略.........
开发者ID:hashme33,项目名称:BoardToJabber,代码行数:103,代码来源:ThreadKeeper.py


注:本文中的Scheduler.Scheduler.start方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。