• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sched.scheduler函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sched.scheduler函数的典型用法代码示例。如果您正苦于以下问题:Python scheduler函数的具体用法?Python scheduler怎么用?Python scheduler使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: __init__

    def __init__(self):
        if sys.version_info[0] > 2:
            # Nice and easy.
            self._scheduler = sched.scheduler()
            # The documentation says that run() returns the next deadline,
            # but it's not true - it returns the remaining time.
            self._run_scheduler = lambda: self._scheduler.run(blocking=False) + self._scheduler.timefunc()
        else:
            # Nightmare inducing hacks
            class SayNoToBlockingSchedulingException(uavcan.UAVCANException):
                pass

            def delayfunc_impostor(duration):
                if duration > 0:
                    raise SayNoToBlockingSchedulingException('No!')

            self._scheduler = sched.scheduler(time.monotonic, delayfunc_impostor)

            def run_scheduler():
                try:
                    self._scheduler.run()
                except SayNoToBlockingSchedulingException:
                    q = self._scheduler.queue
                    return q[0][0] if q else None

            self._run_scheduler = run_scheduler
开发者ID:antoinealb,项目名称:pyuavcan,代码行数:26,代码来源:node.py


示例2: correctProc

def correctProc(mssqlDict, mongoDict, processDict, queueDict):
  #执行存储过程将源数据导入到SQL中间库
  try:
    UpdateExtensionInfo(mssqlDict)
  except:
    print traceback.format_exc()
    timetuple = datetime.now().timetuple()
    if timetuple.tm_hour <= 6:
      updateScheduler = scheduler(time, sleep)
      #schedule run
      updateScheduler.enter(timedelta(minutes=30).total_seconds(), 1, UpdateExtensionInfo, (mssqlDict, mongoDict, processDict, queueDict))
      updateScheduler.run()
    else:
      sys.exit()
  #删除Mongo库过期数据
  try:
    dropOriginalData(mongoDict)
  except:
    print traceback.format_exc()
    timetuple = datetime.now().timetuple()
    if timetuple.tm_hour <= 6:
      updateScheduler = scheduler(time, sleep)
      #schedule run
      updateScheduler.enter(timedelta(minutes=30).total_seconds(), 1, dropOriginalData, (mongoDict))
      updateScheduler.run()
    else:
      sys.exit()
  #计算更新Mongo库历史行情
  try:
    CorrectAllSecurityInfo(mssqlDict, mongoDict, processDict, queueDict)
  except:
    print traceback.format_exc()
    timetuple = datetime.now().timetuple()
    if timetuple.tm_hour <= 6:
      updateScheduler = scheduler(time, sleep)
      #schedule run
      updateScheduler.enter(timedelta(minutes=30).total_seconds(), 1, CorrectAllSecurityInfo, (mssqlDict, mongoDict, processDict, queueDict))
      updateScheduler.run()
    else:
      sys.exit()

  #更新Mongo库分表信息
  try:
    UpdateSplitSecurityIndex(mssqlDict, mongoDict)
  except:
    print traceback.format_exc()
    timetuple = datetime.now().timetuple()
    if timetuple.tm_hour <= 6:
      updateScheduler = scheduler(time, sleep)
      #schedule run
      updateScheduler.enter(timedelta(minutes=30).total_seconds(), 1, UpdateSplitSecurityIndex, (mssqlDict, mongoDict))
      updateScheduler.run()
    else:
      sys.exit()
开发者ID:ZHENGGUCHUAN,项目名称:Indirection,代码行数:54,代码来源:main.py


示例3: main

def main():
  if (len(sys.argv) - 1) % 3 != 0 or len(sys.argv) < 4:
    yes = raw_input('Would you like to schedule an existing reservation from the database [Y/n]? ').lower()
    if yes == 'y' or yes == '' or yes == 'yes':
      sch = sched.scheduler(time_module.time, time_module.sleep)
      scheduleAllExistingReservations(confirm=True, blocking=True, scheduler=sch)
      sys.exit(1)
    else:
      print 'Please provide name and confirmation code:'
      print '   %s <firstname> <lastname> <confirmation code> [...]' % sys.argv[0]
      sys.exit(1)

  args = sys.argv[1:]
  while len(args):
    (firstname, lastname, code) = args[0:3]
    res = db.findReservation(code)
    if res:
      print 'Reservation %s is already in the system...' % code
    else:
      res = db.addReservation(firstname, lastname, code)
    del args[0:3]

  # global config["SMTP_USER"], config["SMTP_PASSWORD"], config["EMAIL_FROM"], config["EMAIL_TO"], config["SEND_EMAIL"]

  sch = sched.scheduler(time_module.time, time_module.sleep)

  if config["SEND_EMAIL"]:
    if not config["EMAIL_FROM"]:
      config["EMAIL_FROM"] = raw_input('Email from: ');
    if config["EMAIL_FROM"]:
      if not config["EMAIL_TO"]:
        config["EMAIL_TO"] = raw_input('Email to: ');
      if not config["SMTP_USER"]:
        config["SMTP_USER"] = config["EMAIL_FROM"]
      if not config["SMTP_PASSWORD"] and config["SMTP_AUTH"]:
        config["SMTP_PASSWORD"] = getpass.getpass('Email Password: ');
    else:
      config["SEND_EMAIL"] = False

  for res in db.Session.query(Reservation):
    if res.active:
      success = getFlightTimes(res)
      if success:
        displayFlightInfo(res, res.flights, True)
        scheduleAllFlights(res, blocking=True, scheduler=sch)
      else:
        db.isReservationActive(res)
        if res.active:
          db.deleteReservation(res)

  print 'Current time: %s' % DateTimeToString(datetime.now(utc))
  sch.run()
开发者ID:alexbstl,项目名称:southwest-checkin,代码行数:52,代码来源:sw_checkin_email.py


示例4: __init__

 def __init__(self,argv):
   self.gen_ops = {}
   self.once = False
   self.scheduler = sched.scheduler(time.time, time.sleep)
   self.dispatcher = []
   self.config_parser(argv)
   self.generator = noise_generator(self.gen_ops)  # Initialize markov factory and keywords
开发者ID:dismantl,项目名称:NOISE,代码行数:7,代码来源:noise.py


示例5: start_daemon

def start_daemon():
    daemon = sched.scheduler()

    main(daemon)
    _logger.info('daemon %s is running', str(daemon))
    daemon.run()
    _logger.info('daemon %s exited', str(daemon))
开发者ID:LPLWWS,项目名称:pybingwallpaper,代码行数:7,代码来源:main.py


示例6: scheduletask

def scheduletask(ci, nextRuntime):
    s = sched.scheduler(time.time, time.sleep)
    print("shedule time: ", nextRuntime)
    s.enterabs(nextRuntime.timestamp(), 1, scheduleAction)
    print("============== task scheduled")
    s.run()
    print("============== finish running")
开发者ID:maowenzhang,项目名称:xutil,代码行数:7,代码来源:taskschedule-json.py


示例7: __init__

 def __init__(self, clock=None):
     self.nodes = []
     self.automators = AutomatorPool()
     self.buffer_length = 0.1
     self.sched = scheduler(time.time, time.sleep)
     self.default_clock = clock or TempoClock()
     self._stopped = False
开发者ID:ashsrini,项目名称:pythoncollider,代码行数:7,代码来源:timeflow.py


示例8: __init__

 def __init__(self, **kwds):
     threading.Thread.__init__(self, **kwds)
     self.setDaemon(True)
     
     # scheduler for timed signals
     self.scheduler = sched.scheduler(time.time, time.sleep)
     self.condition = threading.Condition()
开发者ID:arcean,项目名称:ohm-plugins-misc,代码行数:7,代码来源:ep.py


示例9: __init__

	def __init__(self, logger, args, options):
		Thread.__init__(self)
		self.logger = logger
		self.args = args
		self.options = options
		self.tasks = scheduler(time.time, time.sleep)
		self.stop_flag = False
开发者ID:justindthomas,项目名称:flower_as,代码行数:7,代码来源:snort.py


示例10: __init__

    def __init__(self, serverAddress, RequestHandlerClass, *args, counts, threads, timeout):
        '''
        Constructs the multiprocess server.RequestHandlerClass
        '''
        assert isinstance(counts, int), 'Invalid processes pool size %s' % counts
        super().__init__(serverAddress, None)
        
        processes, pipes = [], []
        
        schedule = scheduler(time.time, time.sleep)
        def pingProcesses():
            for pipe in pipes: pipe.send(True)
            schedule.enter(timeout, 1, pingProcesses, ())
        schedule.enter(timeout, 1, pingProcesses, ())
        scheduleRunner = Thread(name='Ping processes thread', target=schedule.run)
        scheduleRunner.daemon = True
        scheduleRunner.start()
        
        for k in range(0, counts):
            receiver, sender = Pipe(False)
            
            args = RequestHandlerClass, receiver, threads, 2 * timeout
            process = Process(name='Process %s' % k, target=prepareServer, args=args)
            processes.append(process)
            pipes.append(sender)
            
            process.start()

        self.processes = processes
        self.pipes = deque(pipes)
开发者ID:AtomLaw,项目名称:Ally-Py,代码行数:30,代码来源:server_production.py


示例11: test_enter_concurrent

 def test_enter_concurrent(self):
     q = queue.Queue()
     fun = q.put
     timer = Timer()
     scheduler = sched.scheduler(timer.time, timer.sleep)
     scheduler.enter(1, 1, fun, (1,))
     scheduler.enter(3, 1, fun, (3,))
     t = threading.Thread(target=scheduler.run)
     t.start()
     timer.advance(1)
     self.assertEqual(q.get(timeout=TIMEOUT), 1)
     self.assertTrue(q.empty())
     for x in [4, 5, 2]:
         z = scheduler.enter(x - 1, 1, fun, (x,))
     timer.advance(2)
     self.assertEqual(q.get(timeout=TIMEOUT), 2)
     self.assertEqual(q.get(timeout=TIMEOUT), 3)
     self.assertTrue(q.empty())
     timer.advance(1)
     self.assertEqual(q.get(timeout=TIMEOUT), 4)
     self.assertTrue(q.empty())
     timer.advance(1)
     self.assertEqual(q.get(timeout=TIMEOUT), 5)
     self.assertTrue(q.empty())
     timer.advance(1000)
     support.join_thread(t, timeout=TIMEOUT)
     self.assertTrue(q.empty())
     self.assertEqual(timer.time(), 5)
开发者ID:1st1,项目名称:cpython,代码行数:28,代码来源:test_sched.py


示例12: __init__

    def __init__(self, config_fd):
        """Construct a new Recorder.

        :param config_fd: a readable File-like object for the config file
        """

        # Load the JSON config. We don't do any validation right now
        # but validation will happen as the program runs.
        self.config = json.load(config_fd)

        # Build the list of server objects
        self.server_list = self._build_server_list()

        # Create the SQLite database connection
        self.conn = sqlite3.connect(self.config['database'])
        self._init_database()

        # Create the scheduler
        self.timer = sched.scheduler()
        # Disable collecting data
        self.collecting = False
        # sched task handle so we can cancel it later
        self.collection_task = None
        # Blocking queue used for queueing the servers to be collected
        self.collection_queue = queue.Queue()
        # Queue used to return lists of tuples to be added to the database
        self.sql_insert_queue = queue.Queue()
        # List of threads used to process the collection_queue
        self.collection_threads = None
开发者ID:Bindernews,项目名称:log-users,代码行数:29,代码来源:logusers.py


示例13: main

def main():
    parser = argparse.ArgumentParser(
        description='A distributed cron-like daemon')
    parser.add_argument('-f', dest='foreground', action='store_const',
                        const=False, help='run in foreground')
    args = parser.parse_args()

    if os.geteuid() != 0:
        sys.exit('%s must be run as root.' % os.path.basename(sys.argv[0]))

    context = daemon.DaemonContext(
        pidfile=PIDLockFile('/var/run/megacron.pid'),
        detach_process=args.foreground,
    )
    context.signal_map = {
        signal.SIGINT: _signal_handler,
        signal.SIGTERM: _signal_handler
    }

    with context:
        worker.init_worker()

        events = sched.scheduler(time.time, time.sleep)

        scheduler.check_scheduler(events)

        worker.heartbeat(events)
        worker.update_schedules(events)

        events.run()
开发者ID:BigFav,项目名称:MegaCron,代码行数:30,代码来源:main.py


示例14: startCandle

def startCandle(mssqlDict, mongoList, atOnce = False):
  '''
  历史行情更新进程创建
  '''
  if atOnce:
    candle(mssqlDict, mongoList)

  while True:
    try:
      # Get current datetime
      startTime = datetime.datetime.now()
      timetuple = startTime.timetuple()
      executeTime = datetime.datetime(
        year = timetuple.tm_year,
        month = timetuple.tm_mon,
        day = timetuple.tm_mday,
        hour = setup.setupDict['Candle']['Schedule']['Hour'],
        minute = setup.setupDict['Candle']['Schedule']['Minute'],
        second = setup.setupDict['Candle']['Schedule']['Second'])
      # Execute function next day this time
      if (executeTime < startTime):
        executeTime += datetime.timedelta(days=1)
        print 'Candle next execute time: %s' % executeTime.strftime('%Y-%m-%d %X')
      # Get delta time within next execute time and date time now.
      deltaTime = executeTime - startTime
      scheduleHandle = sched.scheduler(time.time, time.sleep)
      scheduleHandle.enter(deltaTime.total_seconds(), 1, candle, (mssqlDict, mongoList))
      scheduleHandle.run()
    except:
      print traceback.format_exc()
开发者ID:ZHENGGUCHUAN,项目名称:QN_Quotation,代码行数:30,代码来源:QN_Candle.py


示例15: __init__

    def __init__(self):
        self.api = wykop.WykopAPI(klucz, sekret)
        self._auth()
        s=sched.scheduler(time.time,time.sleep)

        def check_for_messages(sc):
            try:
                print "Odświeżam wykop o "+strftime("%H:%M:%S",localtime())
                Notifier.notify("Service started", title="Wykop.pl", appIcon="images.png", sound="default")
                get_from_wypok = self.api.request("mywykop","notifications","JSON")
                for key in get_from_wypok:
                    if key.new ==True:
                        if key.type == "entry_comment_directed":
                            print(key.author+" dodal komentarz")
                            Notifier.notify(key.author+"\ndodal komentarz.", title="Wykop.pl", appIcon="images.png", sound="default", open=key.url)
                        elif key.type=="pm":
                            print("PW od "+key.author)
                            Notifier.notify("PW od\n"+key.author, title="Wykop.pl", appIcon="images.png", sound="default", open=key.url)
                        elif key.type=="observe":
                            print("#stalkujo !"+key.author)
                            Notifier.notify("#stalkujo !"+key.author, title="Wykop.pl", appIcon="images.png", sound="default", open=key.url)

            except:
                self._auth()
            sc.enter(300, 1, check_for_messages, (sc,))
        s.enter(1,1,check_for_messages,(s,))
        s.run()
开发者ID:pawisoon,项目名称:Powiadomienia-z-Wykop.pl-dla-OSX,代码行数:27,代码来源:run.py


示例16: __init__

    def __init__(self):
        super(Conductor, self).__init__()

        # set performance constants
        self.tic_count = 0
        self.time_interval = 60.0 / (TICS_PER_MINUTE * 1.0)

        # load music
        self.pieces = in_c.music.load()
        self.piece_events = in_c.music.build(self.pieces)

        # interprocess stuff
        self.web_process = None
        self.web_q = multiprocessing.Queue()
        self.inc_q = multiprocessing.Queue()

        # event scheduler
        self.scheduler = sched.scheduler(time.time, time.sleep)
        self.tic_event = None

        # initialize player objects
        self.players = {}
        for i in range(0, NUM_PLAYERS):
            player = in_c.player.Player(conductor=self, channel=(i+1))
            self.players[player.uuid] = player

        # create MIDI bridge
        self.audio = in_c.audio.OSC2MIDI(host=OSC_SERVERS[0]['host'], port=OSC_SERVERS[0]['port'])
开发者ID:sbma44,项目名称:in_c_in_python,代码行数:28,代码来源:__init__.py


示例17: open_snap

    def open_snap(self, snap):
        dt = datetime.fromtimestamp(snap['sent'] / 1000)
        ext = self.client.media_type(snap['media_type'], binary=False)
        timestamp = str(snap['sent']).replace(':', '-')
        filename = '{}+{}+{}.{}'.format(timestamp, snap['sender'], snap['id'], ext)
        path = PATH + filename
        if not os.path.isfile(path):
            data = self.client.get_snap(snap['id'])
            with open(path, 'wb') as outfile:
                outfile.write(data)

        snap['path'] = path
        file_path = snap['path']

        # open /dev/null or equivalent so we can redirect stdout/stderr to it
        nullfile = open(os.devnull, 'w')
        scheduler = sched.scheduler(time.time, time.sleep)

        if sys.platform.startswith('linux'):
            p = subprocess.Popen(['xdg-open', file_path], stdout=nullfile, stderr=nullfile, preexec_fn=os.setsid)
        elif sys.platform.startswith('darwin'):
            p = subprocess.Popen(['open', file_path], stdout=nullfile, stderr=nullfile)
        elif sys.platform.startswith('win'):
            p = subprocess.Popen(['start /WAIT', file_path], stdout=nullfile, stderr=nullfile)
        else:
            print 'I don\'t recognize your operating system: {0}'.format(sys.platform)
        self.window.after(snap['time'] * 1000 + 1000, lambda: self.mark_read(snap, p))
        '''
开发者ID:wchill,项目名称:pySnap,代码行数:28,代码来源:gui.py


示例18: __init__

    def __init__(self):
        assert isinstance(self.requestAssembly, Assembly), 'Invalid request assembly %s' % self.requestAssembly
        assert isinstance(self.nameAuthorization, str), 'Invalid authorization name %s' % self.nameAuthorization
        assert isinstance(self.accessHeaders, dict), 'Invalid access headers %s' % self.accessHeaders
        assert isinstance(self.accessUriRoot, str), 'Invalid access URI root %s' % self.accessUriRoot
        assert isinstance(self.accessUri, str), 'Invalid access URI %s' % self.accessUri
        assert isinstance(self.accessParameters, list), 'Invalid access parameters %s' % self.accessParameters
        assert isinstance(self.accessResponseEncoding, str), \
        'Invalid access response encoding %s' % self.accessResponseEncoding
        assert isinstance(self.cleanupTimeout, int), 'Invalid cleanup time out %s' % self.cleanupTimeout

        requestProcessing = self.requestAssembly.create(NO_VALIDATION, request=Request, requestCnt=RequestContent,
                                                        response=Response, responseCnt=ResponseContent)
        assert isinstance(requestProcessing, Processing), 'Invalid processing %s' % requestProcessing
        super().__init__(Function(requestProcessing.contexts, self.process))

        self._requestProcessing = requestProcessing
        self._cache = Cache()

        self._authenticationTimeOut = timedelta(seconds=self.cleanupTimeout)
        schedule = scheduler(time.time, time.sleep)
        def executeCleanup():
            self._cleanInactiveAccesses()
            schedule.enter(self.cleanupTimeout, 1, executeCleanup, ())
        schedule.enter(self.cleanupTimeout, 1, executeCleanup, ())
        scheduleRunner = Thread(name='Cleanup access/sessions thread', target=schedule.run)
        scheduleRunner.daemon = True
        scheduleRunner.start()

        self._contentType = 'text/json'
        self._charSet = 'utf-8'
        self._unauthorizedAccess = b'{"code":"401","message":"Unauthorized access"}'
        self._invalidAccess = b'{"code":"401","message":"Invalid authorization"}'
        self._forbiddenAccess = b'{"code":"403","message":"Forbidden access"}'
        self._notFound = b'{"code":"404","message":"Not Found"}'
开发者ID:gizm0bill,项目名称:Ally-Py,代码行数:35,代码来源:security.py


示例19: test_cancel_concurrent

 def test_cancel_concurrent(self):
     q = queue.Queue()
     fun = q.put
     timer = Timer()
     scheduler = sched.scheduler(timer.time, timer.sleep)
     now = timer.time()
     event1 = scheduler.enterabs(now + 1, 1, fun, (1,))
     event2 = scheduler.enterabs(now + 2, 1, fun, (2,))
     event4 = scheduler.enterabs(now + 4, 1, fun, (4,))
     event5 = scheduler.enterabs(now + 5, 1, fun, (5,))
     event3 = scheduler.enterabs(now + 3, 1, fun, (3,))
     t = threading.Thread(target=scheduler.run)
     t.start()
     timer.advance(1)
     self.assertEqual(q.get(timeout=TIMEOUT), 1)
     self.assertTrue(q.empty())
     scheduler.cancel(event2)
     scheduler.cancel(event5)
     timer.advance(1)
     self.assertTrue(q.empty())
     timer.advance(1)
     self.assertEqual(q.get(timeout=TIMEOUT), 3)
     self.assertTrue(q.empty())
     timer.advance(1)
     self.assertEqual(q.get(timeout=TIMEOUT), 4)
     self.assertTrue(q.empty())
     timer.advance(1000)
     support.join_thread(t, timeout=TIMEOUT)
     self.assertTrue(q.empty())
     self.assertEqual(timer.time(), 4)
开发者ID:1st1,项目名称:cpython,代码行数:30,代码来源:test_sched.py


示例20: __init__

 def __init__(self):
     self.t = 0
     self.cpu_clock = 1024 #12*1024
     self.interval = 1.0 / self.cpu_clock
     self.s = sched.scheduler(time.time, time.sleep)
     self.s.enter(self.interval, 1, self.tick, ())
     self.stop = False
开发者ID:athenajc,项目名称:XideSDCC,代码行数:7,代码来源:utils.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python math.const函数代码示例发布时间:2022-05-27
下一篇:
Python scene.Scene类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap