代码之家  ›  专栏  ›  技术社区  ›  WeInThis

Python-调度库-需要繁忙循环

  •  0
  • WeInThis  · 技术社区  · 7 年前

    所以我一直在玩弄时间表,终于把它付诸实施。我太激动了,没有意识到又来了一个问题,哈哈。然而,现在的问题是,它并没有结束时,主要是完成,我真的无法找到解决方案。我知道这件事还在讨论中。睡眠(1)因为每当我输入键盘时,就会出现一个表示时间的错误。睡眠(1)是“问题”,我真的找不到解决它的方法。

    Im使用github的时间表: https://github.com/dbader/schedule

    while True:
        UserInput = input('To run Schedule task - Press y\nTo run directly - Press n\n')
    
        if(UserInput == 'y' or UserInput == 'Y'):
            print(Fore.RESET + space)
            TimeUser = input('What time to start script? Format - HH:MM\n')
    
            schedule.every().day.at(TimeUser).do(main)
            wipe()
            print('Schedule starts at: ''' + TimeUser + ' - Waiting for time...')
            idle = int(round(schedule.idle_seconds()))
    
    
    
            while True:
                schedule.run_pending()
                time.sleep(1)
                idle = int(round(schedule.idle_seconds()))
                if(idle < 6.0) and (idle >= 0.0):
                    print('Starting in: ' + str(idle))
    
        elif(UserInput == 'n' or UserInput == 'N'):
            main()
    
    
        print("Wrong input - Try again")
    

    我确实收到了一位非常善良的人的推荐: 调度库需要繁忙的循环。这里真正的问题是OP如何在不阻塞的情况下运行繁忙的循环,库文档中的答案是:在另一个线程中运行它。如果他休息,计划的任务将无法完成

    https://schedule.readthedocs.io/en/stable/faq.html#how-to-continuously-run-the-scheduler-without-blocking-the-main-thread

    我仍然不明白如果不堵住主管道该怎么办。可能有人知道吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Rach Sharp    7 年前

    run_continuously() 方法。然后,您可以在调度程序上调用该方法一次,然后在主线程中执行任何您喜欢的操作,而无需定期调用 run_pending()

    按下Ctrl+C组合键时出现的错误不是问题,只是抱怨 sleep 在您手动终止时被中断。如果您想根据某些条件自动退出,可以根据循环中的某些逻辑来执行此操作

    例如。 while not terminate: 其中terminate是您设置的一个变量,可能是全局变量,可以通过计划任务更改。

    这种基于时间表的模型的许多实用性都是用于长时间重复运行的后台任务。假设您想执行更多的代码,或者您有一些代码需要运行一次,并且可能在您进入 while 循环,或者您希望重复运行它,也可以将其添加到计划中。

    一些例子

    import schedule
    import threading
    import time
    
    # this is a class which uses inheritance to act as a normal Scheduler,
    # but also can run_continuously() in another thread
    class ContinuousScheduler(schedule.Scheduler):
          def run_continuously(self, interval=1):
                """Continuously run, while executing pending jobs at each elapsed
                time interval.
                @return cease_continuous_run: threading.Event which can be set to
                cease continuous run.
                Please note that it is *intended behavior that run_continuously()
                does not run missed jobs*. For example, if you've registered a job
                that should run every minute and you set a continuous run interval
                of one hour then your job won't be run 60 times at each interval but
                only once.
                """
                cease_continuous_run = threading.Event()
    
                class ScheduleThread(threading.Thread):
                    @classmethod
                    def run(cls):
                        # I've extended this a bit by adding self.jobs is None
                        # now it will stop running if there are no jobs stored on this schedule
                        while not cease_continuous_run.is_set() and self.jobs:
                            # for debugging
                            # print("ccr_flag: {0}, no. of jobs: {1}".format(cease_continuous_run.is_set(), len(self.jobs)))
                            self.run_pending()
                            time.sleep(interval)
    
                continuous_thread = ScheduleThread()
                continuous_thread.start()
                return cease_continuous_run
    
    # example using this custom scheduler that can be run in a separate thread
    your_schedule = ContinuousScheduler()
    your_schedule.every().day.do(print)
    
    # it returns a threading.Event when you start it.
    halt_schedule_flag = your_schedule.run_continuously()
    
    # you can now do whatever else you like here while that runs
    
    # if your main script doesn't stop the background thread, it will keep running
    # and the main script will have to wait forever for it
    
    # if you want to stop it running, just set the flag using set()
    halt_schedule_flag.set()
    
    # I've added another way you can stop the schedule to the class above
    # if all the jobs are gone it stops, and you can remove all jobs with clear()
    your_schedule.clear()
    
    # the third way to empty the schedule is by using Single Run Jobs only
    # single run jobs return schedule.CancelJob
    
    def job_that_executes_once():
        # Do some work ...
        print("I'm only going to run once!")
        return schedule.CancelJob
    
    # using a different schedule for this example to avoid some threading issues
    another_schedule = ContinuousScheduler()
    another_schedule.every(5).seconds.do(job_that_executes_once)
    halt_schedule_flag = another_schedule.run_continuously()
    

    我会注意到您是否真的需要为此使用线程-如果您只是希望程序在完成一次作业后退出,那么您需要做的只是:

    while schedule.jobs:
        schedule.run_pending()
        time.sleep(1)
    

    CancelJob . 不过,我们已经在repl中进行了测试,希望该示例对修补有用。它和一切都应该与Python 3一起工作。