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


Python sched.scheduler函数代码示例

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


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


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